What does this piece of code do?

Question:

Given the following code snippet:

bool foo(int n) {
   for(int i=3;i<sqrt(n)+0.5;i+=2)
      {
        if((n%i)==0){
          return false;
         }
      }
   return true;
}

Can you figure out what the purpose of the foo function is?

Well, at first glance, it might seem that foo is checking for prime numbers, but it is not. I wrote a small test program and got this output:

foo returns true for these numbers from 1 to 100:

1 2 3 4 5 6 7 8 10 11 13 14 16 17 19 20 22 23 26 28 29 31 32 34 37 38 41 43 44 4 6 47 52 53 58 59 61 62 64 67 68 71 73 74 76 79 82 83 86 88 89 92 94 97

foo returns false for these numbers from 1 to 100:

9 12 15 18 21 24 25 27 30 33 35 36 39 40 42 45 48 49 50 51 54 55 56 57 60 63 65 66 69 70 72 75 77 78 80 81 84 85 87 90 91 93 95 96 98 99 100

I can't figure out what foo is doing from the series.

+3
source share
4

, , .. , .

, true, , , . , true, - , .

, n % 2 && foo(n).

+14

true, n , 1, n , , 2 n/2. ( : , . : true, n , sqrt (n), 1, , , 2.)

( , , : 2 .)

+4

, , .

, , 1 . , 2 .

++ :

#include <iostream>
#include <cmath>
#define MAX 1000

bool foo(int n) {
   for(int i=3;i<sqrt(n)+0.5;i+=2)
      {
        if((n%i)==0){
          return false;
         }
      }
    return true;

}

int isprime(int num){ /*Sieve of eratosthenes */

if(num == 1) return false;
bool Primes[MAX+1] = {0};
bool flag;

for(int i=2;i*i<=MAX;i++)
   if(Primes[i] == 0)
     for(int j=2*i;j<=MAX;j+=i)
        Primes[j] = 1;

return !Primes[num];
}

int main(void){
   int Count = 1;
   std::cout<<2<<" ";
   for(int i=2;i<=MAX;i++){
       if((i % 2) && foo(i)){std::cout<<i<<" ";
        Count++;
      }
  }
  std::cout<<"\nCount :"<<Count<<"\n\n\n";

 Count ^= Count;
 for(int i=1;i<=MAX;i++){
    if(isprime(i) == true){std::cout<<i<<" ";
    Count++;
    }
}
std::cout<<"\nCount :"<<Count<<"\n\n\n";

return 0;
}

!

+4

, Trac.

+2
source

Source: https://habr.com/ru/post/1723569/


All Articles