Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package problems;
- public class Problem_010d {
- /*
- * Wow, this one is also quite fast and it doesn't use an array at all! Very clever code from a guy called blub123... lol...
- *
- */
- // main
- public static void main(String[] args) {
- sumPrimesUnder(20000000,1); // Print the final sum.
- }
- public static long sumPrimesUnder (long input, int a){
- long testrange = input;
- long answer = primeAdder(testrange);
- if(a == 1){ // Switch to suppress message or not. Good if being used in another code.
- System.out.print("The sum of all primes under " + testrange +" is: " + answer +".");
- }
- return answer;
- }
- public static long primeAdder(long testrange){
- // This method sends numbers into the isPrime method to check if they are prime, add them to a counter variable if they are and then return the sum.
- long result = 0; // Create a counter.
- // algorithm
- for (int number = 0; number < testrange; number++) { // For all Number = 0, up to 1000000, incrementing by two.
- if (isPrime(number)) { // Call the primechecking method on the number.
- result += number; // If the primechecking method returns true, then add the number to the counter variable "result".
- }
- }
- return result;
- }
- // functions
- // checks if a number is a prime
- public static boolean isPrime(int number) { // This is a boolean method, returns true or false.
- if (number < 2) { // If the number is less than two, return false.
- return false;
- } else if (number == 2) { // If the number equals to, return true. Because 2 is prime, duh.
- return true;
- } else if (number % 2 == 0 || number % 3 == 0 || number % 5 == 0 || number % 7 == 0 || number % 11 == 0 || number % 13 == 0 || number % 5 == 17) {
- // If the number is divisible by 2,3 or 5, return false. (This makes checking if even numbers are prime fast.
- return false;
- } else { // End of IF statement, start of ELSE.
- for (int divisor = 3; divisor <= Math.sqrt(number); divisor += 2) { // For divisor 3 up to and including the square-root of the number, increment by two and check following:
- if (number % divisor == 0) { // If the number is divisble by the divisor we are checking, return false.
- return false; // I was always trying to implement the root limit myself, but I always did it wrong and go some weird results.
- }
- }
- return true; // If the flow of execution reaches here, all divisors up to the root of the number we are testing for
- // have been tried, and therefore the number must be a prime.
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement