C Exercise Example 14 - Decompose a positive integer into prime factors
Title:Decompose a positive integer into prime factors. For example: input 90, print out90=2*3*3*5。
Program analysis:To decompose n into prime factors, first find the smallest prime number k, then complete the following steps:
- (1) If this prime number is exactly equal to n (when it is less than n, continue executing the loop), then the process of decomposing prime factors has ended, and just print it out.
- (2) But if n is divisible by k, then print the value of k, and use the quotient of n divided by k as the new positive integer n. Repeat the second step.
- (3) If n cannot be divided by k, then use k+1 as the value of k, and repeat the first step.
Example
// Created by www.example.com on 15/11/9.
// Copyright © 2015 Example. All rights reserved.
//
#include<stdio.h>
int main()
{
int n,i;
printf("Please enter an integer:");
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 output of the above example is:
请输入整数:90 90=2*3*3*5other extensions