gpt4 book ai didi

c - 寻找等于自己个数的因数之和

转载 作者:行者123 更新时间:2023-11-30 14:36:22 26 4
gpt4 key购买 nike

我正在努力完成作业,但有些事情困住了我。

问题来了:在N范围内,按如下格式输出因数之和等于其自身的数。

输入:

1000

输出:

6 its factors are 1 2 3 
28 its factors are 1 2 4 7 14
496 its factors are 1 2 4 8 16 31 62 124 248

这是我的代码,请告诉我为什么我不能得到正确的输出。欣赏它,如果你可以帮我改进它。

提前致谢。

#include<stdio.h>
#define NUM 100
int main()
{
int goal[NUM];//array for factors.
int N;
scanf("%d",&N);
getchar();
for(int p=2;p<N;p++)//1 and N are not included.
{
int j=0,sum=0;
for(int i=1;i<p; )
{
//get factors and put them into array.
while(p%i==0)
{
goal[j]=i;
sum+=goal[j];
j++;
i++;
}
}
//judge the sum of factors and p the two values are equal.
if(sum==p)
{
printf("%d its factors are ",p);

for(int i=0;i<j;i++)
{
while(i==j-1)
printf("%d \n",goal[i]);
}
}
}
return 0;

}

最佳答案

让其变得干净一点,

int main()
{
int N, factors_sum, factors_cnt, num, j;

scanf("%d", &N);

int *factors = malloc(sizeof(int) * N/2);

if (factors == NULL)
{
perror("malloc(2)");
return 1;
}

for (num = 2 ; num < N ; ++num)
{
factors_cnt = 0;
factors_sum = 0;
for (j = 1 ; j <= num/2 ; ++j)
if (num % j == 0)
factors_sum += (factors[factors_cnt++] = j);

if (factors_sum == num)
{
printf("%d its factors are", num);
for (j = 0 ; j < factors_cnt ; ++j)
printf(" %d", factors[j]);
printf("\n");
}
}
free(factors);
return 0;
}

保留代码的修改:

#include<stdio.h>
#define NUM 100
int main()
{
int goal[NUM];//array for factors.
int sum=0;
int N;
scanf("%d",&N);
//getchar(); // I donno why you need this, better to remove it
for(int p=2;p<N;p++)//1 and N are not included.
{
// sum is different for every number
// need to be set to 0 individually for every number
sum = 0;
int j=0;
for(int i=1;i<p; i++) // i++ everytime
{
//get factors and put them into array.
if (p%i==0)
// changed while to if
// while would keep executing forever
{
goal[j]=i;
sum+=goal[j];
j++;
}
}
//judge the sum of factors and p the two values are equal.
if (sum==p)
{
printf("%d its factors are ",p);

for(int i=0;i<j;i++)
{
// no need for while here
printf("%d \n",goal[i]);
}
}
}
return 0;

}

我已对您的代码进行了修改,并纠正/评论了您所犯的错误。

关于c - 寻找等于自己个数的因数之和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58102879/

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