Write a Python Program to find the Prime Factors of a Number using the For Loop, and While Loop with an example.
Python Program to find Prime Factors of a Number using For Loop
This Python program allows the user to enter any positive integer. Next, the below code returns the prime factors of that number using the For Loop.
TIP: I suggest you refer to Python program for Factors of a Number, and Python Program for Prime Number articles to understand this program logic.
Number = int(input(" Please Enter any Number: "))
for i in range(2, Number + 1):
if(Number % i == 0):
isprime = 1
for j in range(2, (i //2 + 1)):
if(i % j == 0):
isprime = 0
break
if (isprime == 1):
print(" %d is a Prime Factor of a Given Number %d" %(i, Number))

Prime Factors of a Number using While Loop
This Prime Factors of a Number program is the same as the above. In this Python example, we replaced Python For Loop with Python While Loop
Number = int(input(" Please Enter any Number: "))
i = 1
while(i <= Number):
count = 0
if(Number % i == 0):
j = 1
while(j <= i):
if(i % j == 0):
count = count + 1
j = j + 1
if (count == 2):
print(" %d is a Prime Factor of a Given Number %d" %(i, Number))
i = i + 1
The Prime Factors of a Number output.
Please Enter any Number: 250
2 is a Prime Factor of a Given Number 250
5 is a Prime Factor of a Given Number 250
Also Read