Optimizing prime numbers code?

后端 未结 9 1777
别那么骄傲
别那么骄傲 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: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;
    }
    

提交回复
热议问题