Prime number calculation fun

前端 未结 18 1760
深忆病人
深忆病人 2020-12-05 15:32

We\'re having a bit of fun here at work. It all started with one of the guys setting up a Hackintosh and we were wondering whether it was faster than a Windows Box of (nearl

18条回答
  •  时光取名叫无心
    2020-12-05 16:03

    Well I see a couple of quick optimizations that can be done. First you don't have to try each number up to half of the current number.

    Instead you only have try up to the square root of the current number.

    And the other optimization was what BP said with a twist: Instead of

    int count = 0;
    ...
    for (int i = 2; i < top; i++)
    ...
    if (current == 2)
      current++;
    else
      current += 2;
    

    use

    int count = 1;
    ...
    for (int i = 3; i < top; i += 2)
    ...
    current += 2;
    

    This should speed things up quite a lot.

    Edit:
    More optimization courtesy of Joe Pineda:
    Remove the variable "top".

    int count = 1;
    ...
    for (int i = 3; i*i <= current; i += 2)
    ...
    current += 2;
    

    If this optimization indeed increases speed is up to java.
    Calculating the square root takes a lot of time compared to multiplying two numbers. However since we move the multiplication into the for loop this is done every single loop. So this COULD slow things down depending on how fast the square root algorithm in java is.

提交回复
热议问题