In this article we will show you, How to Write Python Program to find Prime Factors of a Number using For Loop, and While Loop with example.
TIP: I suggest you to refer Factors of a Number, and Prime Number articles to understand the logic.
Python Program to find Prime Factors of a Number using For Loop
This python program allows the user to enter any positive integer. Next, it will return the prime factors of that number using the For Loop.
# Python Program to find Prime Factors of a Number 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))
OUTPUT
Python Program to Display Prime Factors of a Number using While Loop
This program is same as above. Here, we replaced For Loop with While Loop
# Python Program to find Prime Factors of a Number 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
OUTPUT