SummationOfPrimes.java 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /* The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
  2. Find the sum of all the primes below two million.
  3. */
  4. import java.lang.ArithmeticException;
  5. public class SummationOfPrimes {
  6. private long num;
  7. private long sum;
  8. public SummationOfPrimes(long num) {
  9. this.num = num;
  10. this.setSum();
  11. }
  12. public long getSum() {
  13. return this.sum;
  14. }
  15. private void setSum() {
  16. long sum = 0;
  17. for (long i = 0; i < this.num; i++) {
  18. if ( isPrime(i) ) {
  19. sum += i;
  20. }
  21. else
  22. continue;
  23. }
  24. this.sum = sum;
  25. }
  26. // Helper function to find prime numbers
  27. private static boolean isPrime(long num) {
  28. // Zero and one aren't prime numbers
  29. if (num == 0 || num == 1)
  30. return false;
  31. // Two is a prime number
  32. else if (num == 2)
  33. return true;
  34. /* To only check numbers greater than one and less than the
  35. passed-in number */
  36. else {
  37. for (long i = 2; i < num; i++) {
  38. if (num % i == 0)
  39. return false;
  40. }
  41. }
  42. // Any number that doesn't trigger any of the previous conditions is prime
  43. return true;
  44. }
  45. }