Optimizing prime numbers code?

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

    If you just want primes below 100, there's no need to write code to compute them. It's perhaps a stupid answer, but it solves your problem as stated efficiently and concisely.

    int main() {
        cout << "Prime numbers are:" << endl << "2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97" << endl;
        return 0;
    }
    
    0 讨论(0)
  • 2021-01-25 02:39
    /*** Return an array of primes from 2 to n. ***/
    int[] function nPrimes(int n) {
       int primes[];  //memory allocation may be necessary depending upon language.
       int p = 0;
       bool prime;
       for (int i = 2; i <= n; i++) {
           prime = true;
           //use (j <= (int)sqrt(i)) instead of (j < i) for cost savings.
           for (int j = 2; j <= (int)sqrt(i); j++)  {
               if (i % j == 0) {
                   prime = false;
                   break;
               }
           }
           if (prime) {
               primes[p++] = i;
           }    
       }
       return primes;
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题