gpt4 book ai didi

c - 得到结果多 1,除数计数 程序 - C

转载 作者:行者123 更新时间:2023-11-30 19:11:13 25 4
gpt4 key购买 nike

Write a program which reads in an integer k, and prints out the number of positive integers between 1 and 100000 (inclusive) which have exactly k divisors.

    #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。(参见:你通过添加 2 来计算除数的数量,因为所有数字都可以有只有偶数个除数。)

问题出在这个声明中:

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

特别是在表达式中

        i<sqrt(N)

其中排除 sqrt(N) 可能的除数。

但是对于整数的2次方的数字(如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//
}

关于c - 得到结果多 1,除数计数 程序 - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40499037/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com