Write a Python Program to find Prime Factors of a Number using 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, Python returns the prime factors of that number using the For Loop.
TIP: I suggest you refer Factors of a Number, and Prime Number articles to understand this python program logic.
# 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))
Python Program to Display Prime Factors of a Number using While Loop
This Python Prime Factors of a Number program is the same as the above. In this Python example, 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
Python 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