Question

I need a JAVA code for the below assignment 1) Write a program that takes a...

I need a JAVA code for the below assignment

1) Write a program that takes a whole number input from a user and determines whether it’s prime. If the number is not prime, display its unique prime factors. Remember that a prime number’s factors are only 1 and the prime number itself. Every number that’s 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.

0 0
Add a comment Improve this question Transcribed image text
Answer #1
//PrimeFactors.java
import java.util.*;

public class PrimeFactors{
  private static boolean isPrime(int n){
    for(int i = 2;i<n;i++){
      if(n%i == 0) {
        return false;
      }
    }
    return true;
  }

  public static void main(String args[]){
    int n,i = 2,input;
    ArrayList<Integer> queue = new ArrayList<Integer>();
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter n: ");
    n = scanner.nextInt();
    input = n;

    if(isPrime(input)){
      System.out.println(input+" is prime number");
    }
    else {
      while (n > 1) {
        if (isPrime(i)) {
          while (n % i == 0) {
            queue.add(i);
            n = n / i;
          }
        }
        i++;
      }

      System.out.print("Prime factors for " + input + ": ");
      for(i = 0;i<queue.size();i++){
        System.out.print(queue.get(i)+ " ");
      }
    }
  }
}
Add a comment
Know the answer?
Add Answer to:
I need a JAVA code for the below assignment 1) Write a program that takes a...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT