How can I test for primality?

前端 未结 16 2216
南方客
南方客 2020-12-05 08:29

I am writing a little library with some prime number related methods. As I\'ve done the groundwork (aka working methods) and now I\'m looking for some optimization. Ofcours

16条回答
  •  盖世英雄少女心
    2020-12-05 08:51

    I guess this is your problem:

    for (int idx = 3; idx < flooredAndSquared; idx++)
    

    This should be

    for (int idx = 3; idx <= flooredAndSquared; idx++)
    

    so you don't get square numbers as primes. Also, you can use "idx += 2" instead of "idx++" because you only have to test odd numbers (as you wrote in the comment directly above...).

提交回复
热议问题