Optimizing prime numbers code?

后端 未结 9 1756
别那么骄傲
别那么骄傲 2021-01-25 01:53

I wrote this code to show the primes between 1 and 100. The only condition is to do not use functions, whole code should be inline. I would ask if I can improve (optimize) it mu

9条回答
  •  囚心锁ツ
    2021-01-25 02:31

    You could optimise your existing code:

    • In the while loop you should have a step of 2, so that you do not test the even numbers.
    • In your for loop you should stop when you reach the square root of the number you are testing

    You could use a different method:

    • Sieve of Erastoses: http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

    On the Sieve of Erastoses just removing the numbers divisable by 2,3 and 5 would significantly reduce the number of times you need to test for primality.

提交回复
热议问题