Latest web development tutorials

C Exercise Example 14 - Set a positive integer decomposition of the quality factor

100 cases of classic C language 100 cases of classic C language

Title: a positive integer decomposition of the quality factor. For example: Enter 90 to print out 90 = 2 * 3 * 3 * 5.

Program analysis: the decomposition of n quality factor, you should first find a smallest prime number k, then according to the following steps:

  • (1) If the prime number exactly equal to (less than the time to continue the cycle) n, then the decomposition of the quality factor of the process has been completed, in addition to print out.
  • (2) but k n be divisible should print out the value of k, k with n divided by the quotient, as a new positive integer n. Repeat Step.
  • (3) if n is not divisible by k, k + 1 is used as the value of k, repeat the first step.
//  Created by www.w3big.com on 15/11/9.
//  Copyright © 2015年 本教程. All rights reserved.
//

#include<stdio.h>
int main()
{
    int n,i;
    printf("请输入整数:");
    scanf("%d",&n);
    printf("%d=",n);
    for(i=2;i<=n;i++)
    {
        while(n%i==0)
        {
            printf("%d",i);
            n/=i;
            if(n!=1) printf("*");
        }
    }
    
    printf("\n");
    return 0;
}

The above example output is:

请输入整数:90
90=2*3*3*5

100 cases of classic C language 100 cases of classic C language