djmattyg007

Project Euler Problem 3 - does work

Sep 30th, 2013
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.45 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.Collections;
  3.  
  4. public class PESolver3
  5. {
  6.     public static void main(String[] args)
  7.     {
  8.         ArrayList<Long> factors = PESolver3.getFactors(Long.parseLong(args[0]));
  9.         Collections.sort(factors, Collections.reverseOrder());
  10.         if (factors != null) {
  11.             for (Long factor : factors) {
  12.                 System.out.print(factor + ": ");
  13.                 if (PESolver3.isPrime(factor)) {
  14.                     System.out.println("prime");
  15.                 } else {
  16.                     System.out.println("not prime");
  17.                 }
  18.             }
  19.         }
  20.     }
  21.  
  22.     public static ArrayList<Long> getFactors(long num)
  23.     {
  24.         if (num < 1) {
  25.             return null;
  26.         } else if (num == 1) {
  27.             ArrayList<Long> factors = new ArrayList<Long>();
  28.             factors.add(1L);
  29.             return factors;
  30.         }
  31.  
  32.         ArrayList<Long> factors = new ArrayList<Long>();
  33.         Double tmpRoot = new Double(Math.ceil(Math.sqrt(num)));
  34.         long root = tmpRoot.longValue();
  35.         for (long x = 1L; x <= root; x++) {
  36.             if (num % x == 0) {
  37.                 if (!factors.contains(x)) {
  38.                     factors.add(x);
  39.                 }
  40.                 Long x2 = (long) (num / x);
  41.                 if (!factors.contains(x2)) {
  42.                     factors.add(x2);
  43.                 }
  44.             }
  45.         }
  46.  
  47.         return factors;
  48.     }
  49.  
  50.     public static boolean isPrime(long num)
  51.     {
  52.         if (num <= 1) {
  53.             return false;
  54.         } else if (num == 2) {
  55.             return true;
  56.         }
  57.         Double tmpRoot = new Double(Math.ceil(Math.sqrt(num)));
  58.         long root = tmpRoot.longValue();
  59.         for (long x = 2; x <= root; x++) {
  60.             if (num % x == 0) {
  61.                 return false;
  62.             }
  63.         }
  64.         return true;
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment