Search code examples
cfactorization

Prime Factorization


So my professor has us writing a program that fines the prime facotrization of a number given by the user. And provide the answer in exponents. So if your number was 96, I have the program listing out like this 2 x 2 x 2 x 2 x 3. He would like us to have it listed out like this. 2^5 x 3^1. How would I go about doing this?

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

Solution

  • You could do this by introducing a while loop inside the if block and count the power of the current prime factor and print it there itself.

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