计算素数分解的程序

我想编写一个程序,用计数器而不是scanf查找数字的素因式分解。我已经实现了一些代码,但没有得到想要的结果!

#include<stdio.h>
#define MAX 1000

int main()
{
    int num;
    int counter;
    int factor = 2;

    for (counter = 2; counter <= MAX; counter++) {
        printf("factorazation of number %d is",counter);

        while (factor<counter) {
            int power = 0;
            if (counter%factor == 0) {

                //  int power=0;
                while (counter%factor == 0) {
                    counter = counter / factor;
                    power++;
                }
                printf("%d^%d\n",factor,power);
                if (counter != 1)
                    printf("X");


            }
            factor++;
        }

        if (counter != 1)
            printf("%d^1.\n",factor);

        //  printf("factorazation of number %d is",counter);
    }
}
huhailongshiwo 回答:计算素数分解的程序

您至少有两个错误。

1)您需要在for循环中将factor设置为2

2)在循环中同时修改counter时,不能使用counter获取下一个数字。您需要使用两个变量。

赞:

int current;   
for (current= 2; current<= MAX; current++) {
    factor = 2;         // set factor back to 2
    counter = current;  // make a copy of current into counter
                        // so that it's okay to modify counter inside the loop
    printf("factorazation of number %d is",counter);

此外,您还需要修正\n的使用以获得清晰的打印效果。

本文链接:https://www.f2er.com/3042434.html

大家都在问