Prime Numbers in Java - Algorithms

前端 未结 6 887
南笙
南笙 2021-01-22 15:48

I have started learning to code in Java and decided I would use the Project Euler site to give me little tasks to try and complete with each bit of new coding I learn. So I came

6条回答
  •  无人及你
    2021-01-22 16:48

    There are many ways to improve a program like this, but the improvements have to do mostly with mathematics and not programming:

    • When looking for factors, check each number, not just primes. If you find a factor check if it's prime. You'll save yourself of many primality checks this way.

    • The greatest prime factor of a composite number can be at most the number's square root, so you can stop the iteration earlier.

    • Use a fast primality test instead of doing trial divisions http://en.wikipedia.org/wiki/Primality_test

    Then again, this is a one-off. Don't overcomplicate it.

提交回复
热议问题