Posted By

NerdGnome on 02/19/11


Tagged


Versions (?)

codemk2


 / Published in: C++
 

all better?

  1. //Patrick Liggett Assignment #5 CS161
  2. //This program calculates the number of primes in the first 50 chiliads and the average per chiliad.
  3. //Sources: Nick Minkler- friend. Helped with the algorthim.
  4.  
  5. #include <iostream>
  6. #include <cmath>
  7. #include <iomanip>
  8.  
  9. using namespace std;
  10.  
  11. bool isPrime (long);
  12. long primeCount (long x, long y);
  13.  
  14. int main()
  15. {
  16. long count = 0;
  17. long totalCount = 0;
  18.  
  19. cout << setw(10) << "Start" << "End" << "Number of Primes" << endl;
  20.  
  21. for(long i = 0; i <= 49; i++)
  22. {
  23. count = primeCount (1 + (i * 1000), (i + 1) * 1000);
  24. totalCount += count;
  25. cout << count << i + 1;
  26. cout << 1 + i * 1000 << setw(10) << " " << (i + 1) * 1000 << " " << count;
  27.  
  28. }
  29.  
  30.  
  31. return 0;
  32.  
  33. }
  34.  
  35.  
  36.  
  37.  
  38.  
  39. bool isPrime (long n)
  40. {
  41. bool prime;
  42.  
  43. prime = true;
  44.  
  45. if(n % 2 == 0)
  46. prime = false;
  47.  
  48. for(long i = 3; i < n && prime == true; i += 2)
  49. {
  50. if(n % i == 0)
  51. prime = false;
  52. }
  53. return prime;
  54.  
  55. }
  56.  
  57. long primeCount (long x, long y)
  58. {
  59. long count = 0;
  60.  
  61. for(x; x < y; x++)
  62. {
  63. if(isPrime(x))
  64. count++;
  65. }
  66. return count;
  67. }

Report this snippet  

You need to login to post a comment.