In this section, you will learn how to find the prime factors of the non prime number.
In this section, you will learn how to find the prime factors of the non prime number.In this section, you will learn how to find the prime factors of the non prime number. Here we have prompted the user to enter any number. If the number entered by the user is prime then we have displayed a simple message and if the number is not a prime number we have find all the prime factors of that number. We have also allowed the user to check the numbers as long as they want to do.
Here is the code:
import java.util.*; class CheckPrime { static boolean isPrime(long number) { boolean isPrime = false; int i = (int) Math.ceil(Math.sqrt(number)); while (i > 1) { if ((number != i) && (number % i == 0)) { isPrime = false; break; } else if (!isPrime) isPrime = true; --i; } return isPrime; } public static void main(String[] args) { Scanner input = new Scanner(System.in); int menu = 0; boolean quit = false; System.out.println("1. Check"); System.out.println("2. Exit"); do { System.out.print("Please enter your choice: "); menu = input.nextInt(); System.out.println(); switch (menu) { case 1: System.out.println("Enter number to check: "); long num = input.nextLong(); if (isPrime(num)) { System.out.println("Hello"); } else { System.out.println("Prime Factors are:"); for (int i = 1; i < num; i++) { if (num % i == 0) { if (isPrime(i)) { System.out.println(i); } } } } break; case 2: quit = true; break; } } while (!quit); } }
Output:
1. Check 2. Exit Please enter your choice: 1 Enter number to check: Enter number to check: Please enter your choice: 2 |