2016-11-09 18 views
-1

編寫一個讀入整數k的程序,並打印出正好具有k個除數的1到100000(含)之間的正整數數。獲得結果1個,除數計數程序 - C

#include <stdio.h> 
    #include <stdlib.h> 
    #include <math.h> 

    int main(void){ 
    int k=0, N=0, i=0, r=0, n_divisors=0, result=0; 
    printf("Enter the number of divisors: "); 

/*scanning in an integer value*/ 
    scanf(" %d",&k); 
/*loop to count the no. of divisors in an integer from 1 to 100000*/ 
    for(N=1; N<=100000; N++){ 
      n_divisors=0; 
/*loop for incrementing the no. divisors in an integer by 2 */ 
     for(i=1; i<sqrt(N); i++){ 
/*Testing if i is a divisor of the integer.*/ 
       r=(N%i); 
       if(r==0) 
        n_divisors+=2; 
     } 
/* If the no. of divisors is equal to k, then increment result*/ 
       if(n_divisors==k) 
        result++; 
/* else reset the value of no. of divisors to 0*/ 
    } 
/* printing the value for no. of integers form 1 to 100000 with K no. of divisors*/ 
     printf("There are %d numbers between 1 and 100000 inclusive which have exactly \n",result ); 
     printf("%d divisors.",k); 
    return 0; 
    } 
+1

很奇怪,用C註釋('>註釋/ /')。我的編譯器不喜歡它。 – MarianD

回答

1

這是因爲你想象的更嚴重的正常工作 - 您可能會獲得奇怪的結果,不僅會增加1.(請參閱:您通過添加2,來計算除數的數量,因爲所有數字可能只有張甚至數除數的)

的問題是在此聲明:

 for(i=1; i<sqrt(N); i++){ 

特別是在表達

 i<sqrt(N) 

在其中它排除sqrt(N)從可能的除數。

但對於其中的數字是整數第二功率(如14916,...)的sqrt(N)他們的除數。

所以插入代碼的東西作爲

 if (i * i == N) 
      n_divisors++; 

太感動了你的代碼,然後將如下的部分(我加了正確的壓痕)

// loop to count the no. of divisors in an integer from 1 to 100000 
for(N=1; N<=100000; N++){ 
    n_divisors=0; 
    // loop for incrementing the no. divisors in an integer by 2 
    for(i=1; i<sqrt(N); i++){ 
     // Testing if i is a divisor of the integer. 
     r=(N%i); 
     if(r==0) 
      n_divisors+=2; 
    } 
    if (i * i == N) 
     n_divisors++; 
    // If the no. of divisors is equal to k, then increment result// 
    if(n_divisors==k) 
     result++; 
    // else reset the value of no. of divisors to 0// 
} 
+0

感謝您的反饋,我有一種感覺,對於一系列值而言是嚴重的,但不知道它們在哪裏。 – Omar

0

這對我來說,一旦註釋被移除,因爲它們會導致一些問題

清理代碼

#include <stdio.h> 
#include <stdlib.h> 
#include <math.h> 

int main(void){ 
int k=0, i=0, n_divisors=0, result=0; 
double N=0, r=0; 
printf("Enter the number of divisors: "); 

scanf(" %d",&k); 
for(N=1; N<=100000; N++){ 
    n_divisors=0; 
    for(i=1; i<sqrt(N); i++){ 
     r=fmod(N, i); 
     if(r==0) 
      n_divisors+=2; 
} 
      if(n_divisors==k) 
      result++; 
} 
printf("There are %d numbers between 1 and 100000 inclusive which have exactly\n",result); 
printf("%d divisors.",k); 
return 0; 
} 
+0

對評論感到抱歉,正確的答案應該是結果= 10728。 – Omar

+0

@Omar給出了什麼輸入? –

+0

當k = 16時,結果= 10728,範圍爲1到100000 – Omar

相關問題