Optimizing prime numbers code?

后端 未结 9 1765
别那么骄傲
别那么骄傲 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:43

    Avoid using the square root function, and increment your divisor by 2. Also some tricky things in the i loop to increment your possible prime by 2. Inner loop doesn't even need to check divisibility by 2 since no even numbers will even be tested.

    int i,j,sq;
    int min;
    for(sq = 2; sq <= 10; sq++)
    {
      min = (sq-1)*(sq-1);
      min = min + (min+1)%2; //skip if it's even, so we always start on odd
      for(i = min; i < sq*sq; i+=2)
      {
        for(j = 3; j <= sq; j+=2)
        {
          if (i%j == 0)
            bad;
        }
      }
    }
    

    note that the sq loop doesn't add time because it shrinks the inner loops proportionately.

提交回复
热议问题