Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Write a program in Java that takes a whole number input from a user and determines whether its prime. If the number is not prime,

Write a program in Java that takes a whole number input from a user and determines whether its prime. If the number is not prime, display its unique prime factors. Remember that a prime numbers factors are only 1 and the prime number itself. Every number thats not prime has a unique prime factorization. For example, consider the number 54. The prime factors of 54 are 2, 3, 3 and 3. When the values are multiplied together, the result is 54. For the number 54, the prime factors output should be 2 and 3. Use Sets as part of your solution.

The following is what I have so far, my only confusion is how to add sets into it. A sample output would be greatly appreciated. Thank you.

// Program to print all prime factors import java.io.*; import java.lang.Math; import java.util.Scanner; import java.util.Set; import java.util.HashSet;

class Main {// A function to print all prime factors // of a given number n public static void primeFactors(int n){ // Print the number of 2s that divide n while (n%2==0) { System.out.print(2 + " "); n /= 2; } // n must be odd at this point. So we can // skip one element (Note i = i +2) for (int i = 3; i <= Math.sqrt(n); i+= 2) { // While i divides n, print i and divide n while (n%i == 0) { System.out.print(i + " "); n /= i; } } // This condition is to handle the case whien // n is a prime number greater than 2 if (n > 2) System.out.print(n); } public static void main(String[] args) { int temp; boolean isPrime=true; Scanner scan = new Scanner(System.in); System.out.println("Enter any number:"); //capture the input in an integer int num=scan.nextInt(); scan.close(); for(int i=2;i<=num/2;i++){ temp= num%i; if(temp==0){ isPrime=false; break; } } //If isPrime is truew then the number is prime else not if(isPrime) System.out.println(num + " is a prime number"); else System.out.println(num + " is not a Prime Number"); primeFactors(num); } } /* Output:

Enter any number: 19 19 is a Prime Number

Output 2:

Enter any number: 6 6 is not a Prime Number */

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access with AI-Powered Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions