Java examples for java.lang:int prime
Get the prime factors of a number
//package com.java2s; import java.util.ArrayList; public class Main { /**//w w w . ja v a 2s . c om * Get the prime factors of a number * @param number what number to factorize * @return a list of all prime factors */ public static ArrayList<Integer> getPrimeFactors(int number) { ArrayList<Integer> factors = new ArrayList<Integer>(); ArrayList<Integer> primeNumbers = getPrimeList(number); for (int i = 0; i < primeNumbers.size(); i++) { while (number % primeNumbers.get(i) == 0) { factors.add(primeNumbers.get(i)); number = number / primeNumbers.get(i); i = 0; } } return factors; } /** * Get a list of all primes from 2 to maxCheck * @param maxCheck What maximum number to check * @return A list filled with prime numbers * @post all numbers in the list are prim * @post no numbers in the list are negative */ public static ArrayList<Integer> getPrimeList(int maxCheck) throws IllegalArgumentException { ArrayList<Integer> primeList = new ArrayList<Integer>(); if (maxCheck < 2) { throw new IllegalArgumentException("Smallest prime number is 2"); } for (int i = 2; i < maxCheck; i++) { if (isPrime(i)) { primeList.add(i); } } return primeList; } /** * Check if an integer is Prime * @param input number to check * @return True if number is prime * @post Number is prime if returned true */ public static boolean isPrime(int input) { return isPrime((long) input); } /** * check if a long is Prime * @param input input number to check * @return True if number is prime * @post Number is prime if returned true */ public static boolean isPrime(long input) { if (input < 2) { return false; } // no number y above sqrtx can divide x (except x)) long maxLimit = (long) Math.sqrt(input) + 1; for (int i = 2; i < maxLimit; i++) { if (input % i == 0) { return false; } } return true; } }