素数因子化

时间:2015-02-25 17:48:47

标签: c 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;
}

1 个答案:

答案 0 :(得分:3)

你可以通过在while块内引入if循环并计算当前素因子的功效并将其打印在那里来实现。

#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;
}