Java examples for java.lang:int prime
get Prime Factors
//package com.java2s; public class Main { public static int[] getPrimeFactors(int number) { int index = 0; int[] tempFactors = new int[number]; int[] primeList = getAllPrimeBelowN(number); int temp = number; for (int i = 1; i < primeList.length && primeList[i] <= temp; i++) { if (temp % primeList[i] == 0) { tempFactors[index++] = primeList[i]; while (temp % primeList[i] == 0) { temp = temp / primeList[i]; }/*from www . j ava2s . c om*/ } } int[] primeFactors = new int[index]; System.arraycopy(tempFactors, 0, primeFactors, 0, index); return primeFactors; } /** * return prime list equal or below n * Please notice that element 0 is kept for 1 although 1 is not prime, this is preserved for usage in special occasions * * @param n * @return */ public static int[] getAllPrimeBelowN(int n) { if (n == 1) { return new int[] { 1 }; } int[] temp = new int[n]; boolean[] flags = new boolean[n + 1]; temp[0] = 1; temp[1] = 2; int index = 2; int lastPrime = 2; while (lastPrime < n) { for (int i = 2; i * lastPrime <= n; i++) { flags[i * lastPrime] = true; } boolean found = false; for (int i = lastPrime + 1; i <= n; i++) { if (!flags[i]) { found = true; lastPrime = i; temp[index++] = lastPrime; break; } } if (!found) { break; } } int[] result = new int[index]; System.arraycopy(temp, 0, result, 0, index); return result; } }