Advertisement
brilliant_moves

PrimeFactors.java

Nov 4th, 2015
282
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.21 KB | None | 0 0
  1. /*
  2. Java program that asks the user for an integer and then prints out all its prime factors.
  3.  For example, when the user enters 150, the program should print: 2 3 5 5
  4. */
  5.  
  6. import java.util.Scanner;
  7.  
  8. public class PrimeFactors {
  9.  
  10.     public static boolean isPrime(int k) {
  11.         if (k<2) {
  12.             return false;       // 1 has only 1 unique divisor
  13.         } // end if         // so it's not prime
  14.  
  15.         int sqrt = (int) Math.sqrt(k);  // calculate square root of k
  16.  
  17.         for (int j=2; j<=sqrt; j++) {   // iterate from 2 to root of k
  18.             if (k%j==0) {       // if j is a divisor of k...
  19.                 return false;   // ...k is not prime
  20.             } // end if
  21.         } // end for
  22.  
  23.         return true;            // k is prime
  24.     } // end isPrime
  25.  
  26.     public static String getFactors(int n) {
  27.         String factors = "";
  28.         int nCopy=n;
  29.         int i=2;
  30.         while (i<nCopy) {
  31.             while (isPrime(i) && n%i == 0) {
  32.                 factors += i+" ";
  33.                 n /= i;
  34.             } // while
  35.             i++;
  36.         } // while
  37.         if (factors.equals("")) factors = "prime - no factors";
  38.         return factors;
  39.     } // getFactors
  40.  
  41.     public static void main(String[] args) {
  42.         Scanner in = new Scanner(System.in);
  43.         System.out.print("Enter an integer: ");
  44.         int n = in.nextInt();
  45.         System.out.println( getFactors( n));
  46.     } // main()
  47.  
  48. } // class PrimeFactors
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement