Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Exercise Example 14

Python Exercise Example 14

Python 100 Examples Python 100 Examples

**Question:** 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 number is exactly equal to n, it means the process of prime factorization has ended and you can just print it.
(2) If n<> k, but n is divisible by k, you should print the value of k and use the quotient of n divided by k as the new positive integer n, then repeat the first step.
(3) If n is not divisible by k, use k+1 as the new value of k and repeat step 1.

Program source code:

Example (Python 2.0+)

#!/usr/bin/python

-- coding: UTF-8 --

def

reduceNum

(

n

)

:

print

'

{} =

'

.

format

(

n

)

,

if

not

isinstance

(

n

,

int

)

or

n

<=

0

:

print

'

Please enter a valid number!

'

exit

(

0

)

elif

n

in

[

1

]

:

print

'

{}

'

.

format

(

n

)

while

n

not

in

[

1

]

:

Loop ensures recursion

for

index

in

xrange

(

2

,

n

1

)

:

if

n

%

index

==

0

:

n

/=

index

n equals n/index

if

n

==

1

:

print

index

else

:

index must be a prime number

print

'

{} *

'

.

format

(

index

)

,

break

reduceNum

(

90

)

reduceNum

(

100

)

Example (Python 3.0+)

#!/usr/bin/python3

def

reduceNum

(

n

)

:

print

(

'

{} =

'

.

format

(

n

)

,

end

=

"

"

)

if

not

isinstance

(

n

,

int

)

or

n

<=

0

:

print

(

'

Please enter a valid number!

'

)

exit

(

0

)

elif

n

in

[

1

]

:

print

(

'

{}

'

.

format

(

n

)

)

while

n

not

in

[

1

]

:

Loop ensures recursion

for

index

in

range

(

2

,

n

1

)

:

if

n

%

index

==

0

:

n

//=

index

n equals n//index

if

n

==

1

:

print

(

index

)

else

:

index must be a prime number

print

(

'

{} *

'

.

format

(

index

)

,

end

=

"

"

)

break

reduceNum

(

90

)

reduceNum

(

100

)

The output of the above example is:


90 =  2 * 3 * 3 * 5
100 =  2 * 2 * 5 * 5

Python 100 Examples Python 100 Examples