输出?素数分解

时间:2014-10-04 20:55:01

标签: c

所以我有这个程序,需要它将输出写为“96是2 ^ 5 x 3 ^ 1”而不是2x2x2x2x2x3。

    int main() {

        int i, n;

        // Get the user input.
        printf("Please enter a number.\n");
        scanf("%d", &n);

        // Print header.
        printf("The prime factorization of %d is ", n);

        // Loop through, finding prime factors.
        int cur_factor = 2;
        while (cur_factor < n) {

            // Found a factor.
            if (n%cur_factor == 0) {
                printf("%d x ", cur_factor);
                n = n/cur_factor;

            }

            // Going to the next possible factor.
            else
                cur_factor++;
        }

        // Prints last factor.
        printf("%d.\n", cur_factor);

        return 0;

我需要做什么? 感谢

2 个答案:

答案 0 :(得分:1)

while (cur_factor < n) {

            // Found a factor.
            while (n%cur_factor == 0) {

                n = n/cur_factor;
               count++;
            }
          while(count--)
          printf("%d x ", cur_factor);
          count=0;

            // Going to the next possible factor.
            else
                cur_factor++;
        }

答案 1 :(得分:0)

使用变量power跟踪指数并打印它。

同时使用while循环将n除以cur_factor,直到n无法再被该因素分割。

    int cur_factor = 2;
    int power = 0;
    while (cur_factor < n) {

        // Found a factor.
        while (n % cur_factor == 0) {
            power++;
            n = n/cur_factor;

        }

        // Going to the next possible factor.
        if (power > 0) 
            printf("%d^%d x", cur_factor, power);
        power = 0;
        cur_factor++;
        }
    }