Factoring large numbers is a difficult problem, in part because encryption algorithms use large prime factors to make encryption difficult.
public static void main(String... args) { int nums = 100; for (int i = 0; i < nums; i++) { long start = System.nanoTime(); primeFactors(Long.MAX_VALUE - i); long time = System.nanoTime() - start; if (time > 100e6) System.out.println((Long.MAX_VALUE-i) + " took "+time/1000000+" ms."); } } public static List<Long> primeFactors(long n) { List<Long> factors = new ArrayList<Long>(); while (n % 2 == 0 && n > 0) { factors.add(2L); n /= 2; } for (long i = 3; i * i <= n; i+=2) { while (n % i == 0) { factors.add(i); n /= i; } } if (n > 1) factors.add(n); return factors; }
prints
9223372036854775806 took 3902 ms. 9223372036854775805 took 287 ms. 9223372036854775804 took 8356 ms. 9223372036854775797 took 9519 ms. 9223372036854775796 took 1507 ms. 9223372036854775794 took 111 ms. 9223372036854775788 took 184 ms.
If you replace Long.MAX_VALUE with 1000000000000L, all of them are divided by less than 20 ms.
source share