质因数分解

Prime Factorization

所以我的教授让我们编写一个程序来对用户给定的数字进行质数分解。并以指数形式提供答案。因此,如果您的号码是 96,我将程序列为 2 x 2 x 2 x 2 x 3。他希望我们将其列为这样。 2^5 x 3^1。我该怎么做?

#include <stdio.h>

int main() {

    int i, n;

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

    // Print out factorization
    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;
}

你可以通过在 if 块中引入一个 while 循环来做到这一点,并计算当前质因数的幂并在那里打印出来。

#include <stdio.h>

int main()
{

    int n;

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

    // Print out factorization
    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 )
        {
            int expo = 0;
            while ( n % cur_factor == 0 )
            {
                n = n / cur_factor;
                expo++;
            }
            printf( "%d^%d", cur_factor, expo );
            if ( n != 1 )
            {
                printf( " x " );
            }
        }

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

    // Prints last factor.
    if ( n != 1 )
    {
        printf( "%d^1.\n", cur_factor );
    }
    return 0;
}