Advertisement
Guest User

Untitled

a guest
Oct 13th, 2011
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.86 KB | None | 0 0
  1. #include <iostream>
  2. #include <math.h>
  3. using namespace std;
  4.  
  5. int count_odds(int prime);
  6. int count_evens(int prime);
  7. bool isprime(int test);
  8.  
  9. int main()
  10. {
  11.     int total_odds = 1;   //this value starts at one because we aren't testing the value, 3.
  12.     int total_evens = 1;  //this value starts at one because we aren't testing the value, 2.
  13.     int total_primes = 2;
  14.     int upper_limit;
  15.    
  16.     cout << "until what value should I test primes?" << endl;
  17.     cin >> upper_limit;
  18.    
  19.     for(int i=5; i < upper_limit; i++)
  20.     {
  21.         if(isprime(i))
  22.         {  
  23.             total_odds = total_odds + count_odds(i);
  24.             total_evens = total_evens + count_evens(i);
  25.             total_primes++;
  26.         }
  27.     }
  28.  
  29.     cout << "the total number of primes found was " << total_primes << endl;
  30.     cout << "the number of even digits found was " << total_evens << endl;
  31.     cout << "the number of odd digits found was " << total_odds << endl;
  32.  
  33. return 0;
  34. }
  35.  
  36. /*
  37. purpose: test for primality
  38. input:   int test
  39. output   bool
  40. */
  41. bool isprime(int test)
  42. {
  43.     if(test % 2 == 0)
  44.     {
  45.         return false;
  46.     }
  47.     double square = sqrt(test);
  48.     for(int i  = 3; i < square + 1; i+=2)
  49.     {
  50.         if(test % i == 0)
  51.         {
  52.             return false;
  53.         }
  54.     }
  55.     return true;
  56. }
  57.  
  58. /*
  59. purpose: count the odd digits of a prime
  60. input  : a prime number
  61. output : the number of odd digits of that prime
  62. */
  63. int count_odds(int prime)
  64. {
  65.     int odds = 0;
  66.     int final_digit;
  67.     while(prime != 0)
  68.     {
  69.         final_digit = prime % 10;
  70.         if(final_digit % 2 == 1)
  71.         {
  72.             odds++;
  73.         }
  74.         prime = ((prime - (prime % 10))/10);
  75.     }
  76.     return odds;
  77. }
  78.  
  79. /*
  80. purpose: count the odd digits of a prime
  81. input  : a prime number
  82. output : the number of odd digits of that prime
  83. */
  84. int count_evens(int prime)
  85. {
  86.     int evens = 0;
  87.     int final_digit;
  88.     while(prime != 0)
  89.     {
  90.         final_digit = prime % 10;
  91.         if(final_digit % 2 == 0)
  92.         {
  93.             evens++;
  94.         }
  95.         prime = ((prime - (prime % 10))/10);
  96.     }
  97.     return evens;
  98. }
  99.  
  100.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement