繁体   English   中英

素因数分解

[英]Prime Factorization

因此,我的教授让我们编写了一个程序,该程序可以对用户给定的数字进行最原始化。 并提供指数的答案。 因此,如果您的电话号码是96,我将程序列出为2 x 2 x 2 x 2 x3。他希望我们将其列出为这样。 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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM