C Language Programming Introduction Question-No.14

Topic: Factorize a positive integer. For example: enter 90 and print 90 = 2 3 3 * 5.

Program analysis: To decompose prime factors for n, first find a smallest prime number k, and then complete the following steps:
(1) If this prime number is exactly equal to n, it means that the process of decomposing prime factors has ended, just print it out .
(2) If n <> k, but n is divisible by k, you should print out the value of k, and divide the quotient of n by k, as the new positive integer you n,
repeat the first step.
(3) If n is not divisible by k, then use k + 1 as the value of k and repeat the first step.

2. Program source code:

#include <stdio.h>
#include "math.h"
main()
{
    int n, i;
    printf("\nplease input a number:\n");
    scanf("%d", &n);
    printf("%d=", n);
    for (i = 2; i <= n; i++)
    {
        while (n != i)
        {
            if (n % i == 0)
            {
                printf("%d*", i);
                n = n / i;
            }
            else
                break;
        }
    }
    printf("%d", n);
}
Published 678 original articles · praised 343 · 70,000 views

Guess you like

Origin blog.csdn.net/weixin_43627118/article/details/105462604