Cod sursa(job #487423)

Utilizator cont_de_testeCont Teste cont_de_teste Data 25 septembrie 2010 10:36:10
Problema Ciurul lui Eratosthenes Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.42 kb
# include <algorithm>
using namespace std ;

const char FIN[] = "scmax.in", FOU[] = "scmax.out" ;
const int MAX = 100005 ;

int N, sol = 1 ;

int modulo(int a,int b,int c){
    long long x=1,y=a; // long long is taken to avoid overflow of intermediate results
    while(b > 0){
        if(b%2 == 1){
            x=(x*y)%c;
        }
        y = (y*y)%c; // squaring the base
        b /= 2;
    }
    return x%c;
}
long long mulmod(long long a,long long b,long long c){
    long long x = 0,y=a%c;
    while(b > 0){
        if(b%2 == 1){
            x = (x+y)%c;
        }
        y = (y*2)%c;
        b /= 2;
    }
    return x%c;
}
bool Fermat(long long p,int iterations){
    if(p == 1){ // 1 isn't prime
        return false;
    }
    for(int i=0;i<iterations;i++){
        // choose a random integer between 1 and p-1 ( inclusive )
        long long a = rand()%(p-1)+1;
        // modulo is the function we developed above for modular exponentiation.
        if(modulo(a,p-1,p) != 1){
            return false; /* p is definitely composite */
        }
    }
    return true; /* p is probably prime */
}

int main ( void ) {
      freopen ( "ciur.in", "r", stdin ) ;
      freopen ( "ciur.out", "w", stdout ) ;
      scanf ( "%d", &N ) ;
      for ( int i = 3; i <= N; i += 2 ) {
          if ( Fermat ( i, 5 ) ) {
              ++sol ;
          }
      }

      printf ( "%d", sol ) ;

}