Find the highest prime number in a given range

后端 未结 4 494
不知归路
不知归路 2021-01-26 13:52

I need to find the highest prime number in a given range.
Here is my code which works for 0-100 but if I give 0-125 it is showing prime number as 125.

<         


        
4条回答
  •  再見小時候
    2021-01-26 14:48

    The simplest method you can use is dividing a number starting from 3 with an Array filled by a 2, if modulus (%) gives you an an answer else than 0, it's prime. Then after you got a working code think what can I make better ?

    • You could say I want to ignore even numbers! so why iterate over than at all ? just use i = i + 2 (and start by using 3 as seed prime)
    • I divide through too many numbers! do you really need to check 21%11, 21%13, 21%17, 21%19 ? They are always smaller than 2 so lets ignore primes > half of it
    • Optimize more ? how would limit using a root as maximum in your code affect it ? and Why ?
    • Even more ? why couldn't I eliminate all non-primes beforehand and check what's left ?

    Try to apply these on your code, or just google a working version.

提交回复
热议问题