计算素因数分解的程序

Program that count prime factorazation of numbers

我想制作一个程序,用计数器而不是 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);
    }
}

您至少有两个错误。

1) 您需要在 for-loop

中将 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 的使用以获得漂亮的打印效果。