簡體   English   中英

計算數字素數分解的程序

[英]Program that count prime factorazation of numbers

我想制作一個程序,用 counter 而不是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循環內將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的使用以獲得漂亮的打印效果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM