将因子数量存储为C

时间:2016-03-23 16:31:27

标签: c

我正在参加初学者的编程课程,并有一个问题。我想能够输入一个数字,并打印出类似这样的东西

Factors of 36 between 2 and 35: 2 3 4 6 9 12 18 
36 has 7 factors
36 is not a prime number

我的代码到目前为止允许用户输入一个数字,并且可以打印出第一行,但是我无法将因子数量作为变量。

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int num, num2, factors;

    printf("Enter a number: ");
    scanf("%d", &num);
    num2 = num - 1;
    printf("Factors of %d between 2 and %d: ", num, num2);
    for(factors = 2; factors < num; factors++){
        if(num % factors == 0){
            printf("%d ",factors);
            }
        }
    if(num % factors == 0){
        printf("\n");
        printf("%d has factors\n", num);
        printf("%d is not a prime number\n", num);}
}

如果我能弄清楚如何将多个因子作为变量,那么我可以自己得到第三行,但我遇到了麻烦。

任何正确方向的帮助都将受到赞赏。

2 个答案:

答案 0 :(得分:0)

我认为您要问的是如何存储所有因素?

但是,根据您的示例输出,您甚至不需要缓存值,您只需要保留它们的数量。

将变量cnt初始化为0

int cnt = 0;

并在每次看到因素时递增它:

  if(num % factors == 0){
      printf("%d ",factors);
      cnt++;
  }

然后您的第2行输出将是:

printf("%d has %d factors", num, cnt);

然后你可以检查因素的cnt以确定它是否为素数:

bool isPrime = (cnt == 0);
if(isPrime) printf("%d is a prime number", num);
else printf("%d is not a prime number", num);

答案 1 :(得分:0)

算法错误

for()没有提前break,因此在完成循环后,factors == num如果num至少为2。

for(factors = 2; factors < num; factors++){
....
}
// This is really doing `num % num` which is 0, which equals 0, so always true
if(num % factors == 0){

相反,只需计算因素。下半部分类似于@James Wierzba

unsigned count = 0;
for(factors = 2; factors < num; factors++) {
  if(num % factors == 0){
    count++;
    printf("%d ",factors);
  }
}

if (count > 0) {
  printf("%d is not a prime number\n", num);}
}