First of all, I would like to point out that you did not write this code. You stole it from here and claimed that you wrote it, which is incredibly unethical.
The code is correct. It's just slow. As you increase the power, the code takes increasingly longer. There are two reasons why this occurs:
- The Fermat test takes increasingly longer to apply.
- BigInteger operations take increasingly longer to execute.
The Fermat test grows like O(k × log2n × log log n × log log log n). BigInteger's addition and subtraction grow like O(n). Obviously, BigInteger is what is slowing you down.
Below is a profile of your code with the power set from 5 to 7.
If you want your code to produce larger and larger primes, you should focus on reducing the number of operations you do on BigIntegers. Here is one such improvement:
- Take
n.subtract(BigInteger.ONE)
outside of yourfor
loop. The result does not need to be calculated many times.
Further suggestions will have to come from the Mathematics folks over on Mathematics Stack Exchange.