Advertisement
felixnardella

Prime_numbers

Aug 10th, 2021 (edited)
250
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.95 KB | None | 0 0
  1. // Prime_numbers.cpp by Felix Nardella
  2.  
  3. #include <iostream>
  4. #include <ctime>
  5. #include <cstdlib>
  6. #include <cmath>
  7.  
  8. using namespace std;
  9.  
  10. bool controllaprimo(int num) {
  11.        
  12.     if (num==3)
  13.         return true;
  14.        
  15.     if (num<=1||num%3==0)
  16.         return false;
  17.    
  18.     for(int i=5;i*i<=num;i+=6){
  19.         if(num%i==0||num%(i+2)==0)
  20.             return false;
  21.     }
  22.     return true;
  23. }
  24.  
  25. int main (){
  26.     int numero=0;
  27.     int totprimi=1;
  28.     bool primo;
  29.     clock_t start, stop;
  30.     double totalTime;
  31.  
  32.     while(numero<=1){
  33.         cout<<"Inserisci il numero: ";
  34.         cin>>numero;
  35.     }
  36.     start = clock();
  37.     cout<<"I numeri primi da 2 a "<<numero<<" sono:"<<endl;
  38.     cout<<"2"<<" ";
  39.     for(int i=3;i<=numero;i+=2){
  40.         primo=controllaprimo(i);
  41.     if (primo==true){
  42.         cout<<i<<" ";
  43.         totprimi++;}
  44.     }
  45.     stop = clock();
  46.     totalTime = (stop - start) / (double)CLOCKS_PER_SEC;
  47.     cout<<"\nTotale numeri primi trovati: "<<totprimi<<endl;
  48.     cout<<"Totale secondi trascorsi: "<<totalTime<<endl;
  49.     system("pause");
  50.  
  51.  
  52.     return 0;
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement