1 /*
   2  * Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 package org.openjdk.bench.java.util.stream.tasks.PrimesFilter;
  24 
  25 import java.util.ArrayList;
  26 import java.util.List;
  27 
  28 public class PrimesProblem {
  29 
  30     /**
  31      * Factors n into its prime factors. If n is prime,
  32      * the result is a list of length 1 containing n.
  33      *
  34      * @param n the number to be factored
  35      * @return a list of prime factors
  36      */
  37     static List<Long> factor(long n) {
  38         List<Long> flist = new ArrayList<>();
  39 
  40         while (n % 2L == 0) {
  41             flist.add(2L);
  42             n /= 2L;
  43         }
  44 
  45         long divisor = 3L;
  46         while (n > 1L) {
  47             long quotient = n / divisor;
  48             if (n % divisor == 0) {
  49                 flist.add(divisor);
  50                 n = quotient;
  51             } else if (quotient > divisor) {
  52                 divisor += 2L;
  53             } else {
  54                 flist.add(n);
  55                 break;
  56             }
  57         }
  58 
  59         return flist;
  60     }
  61 
  62     /**
  63      * Tests whether n is prime.
  64      *
  65      * @param n the number to be tested
  66      * @return true if n is prime, false if n is composite
  67      */
  68     public static boolean isPrime(long n) {
  69         List<Long> factors = factor(n);
  70         return (factors.size() == 1);
  71     }
  72 
  73 
  74 }