Share on Google+Share on Google+

Find prime factors of non prime number

Ads
In this section, you will learn how to find the prime factors of the non prime number.

Find prime factors of 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:
19
Hello
Please enter your choice: 1

Enter number to check:
26
Prime factors are:
2
13

Please enter your choice: 2

Advertisements

Posted on: May 15, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Ads

Advertisement