C Exercise 14 - Factorize a Positive Integer into Prime Factors
100 Classic C Language Examples
**Problem:** Factorize a positive integer into prime factors. For example: input 90, print 90=233*5.
**Analysis:** To factorize n into prime factors, first find the smallest prime k, then proceed as follows:
- (1) If this prime equals n (when it is smaller, continue the loop), the factorization process is finished; just print it out.
- (2) If n is divisible by k, print the value of k and use the quotient of n divided by k as the new positive integer n. Repeat step 2.
- (3) If n is not divisible by k, use k+1 as the new value of k and repeat step 1.
Example
// Created by www.runoob.com on 15/11/9.
// Copyright (c) 2015 Runoob Tutorial. 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*5