/// <summary> /// Prime factors decomposition /// </summary> /// <param name="n">number to factorize: must be ≥ 2</param> /// <returns>list of prime factors of n</returns> /// <exception cref="MathIllegalArgumentException"> if n < 2.</exception> public static List <Int32> primeFactors(int n) { if (n < 2) { throw new MathIllegalArgumentException(new LocalizedFormats("NUMBER_TOO_SMALL"), n, 2); } // slower than trial div unless we do an awful lot of computation // (then it finally gets JIT-compiled efficiently // List<Integer> out = PollardRho.primeFactors(n); return(SmallPrimes.trialDivision(n)); }
/// <summary> /// Primality test: tells if the argument is a (provable) prime or not. /// <para> /// It uses the Miller-Rabin probabilistic test in such a way that a result is /// guaranteed: it uses the firsts prime numbers as successive base (see /// Handbook of applied cryptography by Menezes, table 4.1). /// </summary> /// <param name="n">number to test.</param> /// <returns>true if n is prime. (All numbers < 2 return false).</returns> public static Boolean isPrime(int n) { if (n < 2) { return(false); } foreach (int p in SmallPrimes.PRIMES) { if (0 == (n % p)) { return(n == p); } } return(SmallPrimes.millerRabinPrimeTest(n)); }
/// <summary> /// Factorization using Pollard's rho algorithm. /// </summary> /// <param name="n">number to factors, must be > 0</param> /// <returns>the list of prime factors of n.</returns> public static List <Int32> primeFactors(int n) { List <Int32> factors = new List <Int32>(); n = SmallPrimes.smallTrialDivision(n, factors); if (1 == n) { return(factors); } if (SmallPrimes.millerRabinPrimeTest(n)) { factors.Add(n); return(factors); } int divisor = rhoBrent(n); factors.Add(divisor); factors.Add(n / divisor); return(factors); }