Java examples for java.lang:Math Prime Number
factorization into prime factors
//package com.java2s; import java.util.ArrayList; public class Main { private static int[] PRIME_NUMBERS = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307 };/* w w w. j av a2 s .c o m*/ /** * factorization into prime factors */ public static int[] getPrimeFactors(int number) { int[] primeNumbers = getPrimeNumbers(number); ArrayList factorList = new ArrayList(); int currentPNIndex = 0; int currentNumber = number; while (true) { if (currentNumber <= 1) { break; } int pn = primeNumbers[currentPNIndex]; if ((currentNumber % pn) == 0) { currentNumber /= pn; factorList.add(new Integer(pn)); continue; } currentPNIndex++; if (currentPNIndex >= primeNumbers.length) { throw new InternalError("failed factorization. : " + number); } } int[] ret = new int[factorList.size()]; for (int i = 0; i < ret.length; i++) { ret[i] = ((Integer) factorList.get(i)).intValue(); } return ret; } /** * make prime number array. */ public static int[] getPrimeNumbers(int upperLimit) { if (upperLimit < 300) { return getPrimeNumbers_small(upperLimit); } return getPrimeNumbers_index(upperLimit); } /** * fastest cache method */ private static int[] getPrimeNumbers_small(int upperLimit) { for (int i = 0; i < PRIME_NUMBERS.length; i++) { if (PRIME_NUMBERS[i] > upperLimit) { int[] ret = new int[i]; for (int j = 0; j < ret.length; j++) { ret[j] = PRIME_NUMBERS[j]; } return ret; } } throw new InternalError("Large? : " + upperLimit); } /** * general array index method */ private static int[] getPrimeNumbers_index(int upperLimit) { if (upperLimit < 2) return new int[0]; boolean[] index = new boolean[upperLimit]; index[0] = true;// not prime number for (int i = 2; i <= upperLimit; i++) { if (index[i - 1] == true) { continue; } for (int j = i * 2; j <= upperLimit; j += i) { index[j - 1] = true; } } int length = 0; for (int i = 1; i < upperLimit; i++) { if (index[i] == false) length++; } int[] ret = new int[length]; int count = 0; for (int i = 1; i < upperLimit; i++) { if (index[i] == false) { ret[count++] = i + 1; } } return ret; } }