Prime Factors of a Number
This program prints prime factors of a number using while loop.
Problem Statement
Write a Java program that prints prime factors of 60 using while loop.
Source Code
| 1 | public class PrimeFactors { |
| 2 | public static void main(String[] args) { |
| 3 | int num = 60; |
| 4 | int i = 2; |
| 5 | while(num > 1) { |
| 6 | if(num % i == 0) { |
| 7 | System.out.println(i + " - Eduinq"); |
| 8 | num /= i; |
| 9 | } else { |
| 10 | i++; |
| 11 | } |
| 12 | } |
| 13 | } |
| 14 | } |
Program Output
2 - Eduinq 2 - Eduinq 3 - Eduinq 5 - Eduinq
Explanation
The program divides the number by smallest prime factor repeatedly until it becomes 1. Each factor is printed. This demonstrates how while loops can extract prime factors. Shows how while loop can print prime factors of a number.