diff --git a/javaProblems/problem17/Readme.md b/javaProblems/problem17/Readme.md new file mode 100644 index 0000000..bac8328 --- /dev/null +++ b/javaProblems/problem17/Readme.md @@ -0,0 +1,42 @@ +# Summation of Primes Problem Statement + +## Problem Description + +Find the sum of all the prime numbers below a given integer. + +The sum of the primes below `10` is `2 + 3 + 5 + 7 = 17.` + +### Input Format + +The program should take a single integer as input: + +``` +N +``` + +### Output Format + +The program should output a single integer: + +``` +SUM +``` + +## Constraints +- `10` ≤ `N` ≤ `2,000,000` + +## Example + +### Input +``` +10 +``` + +### Output +``` +17 +``` + +## Notes + +- The sum of all the prime numbers below 10 is 17. diff --git a/javaProblems/problem17/Solution.java b/javaProblems/problem17/Solution.java new file mode 100644 index 0000000..2283c30 --- /dev/null +++ b/javaProblems/problem17/Solution.java @@ -0,0 +1,24 @@ +public class Solution { + public long sumPrimes(int n) { + boolean[] isPrime = new boolean[n]; + for (int i = 2; i < n; i++) { + isPrime[i] = true; + } + + for (int i = 2; i*i < n; i++) { + if (isPrime[i]) { + for (int j = i*i; j < n; j += i) { + isPrime[j] = false; + } + } + } + + long sum = 0; + for (int i = 2; i < n; i++) { + if (isPrime[i]) { + sum += i; + } + } + return sum; + } +} diff --git a/javaProblems/problem17/Test.java b/javaProblems/problem17/Test.java new file mode 100644 index 0000000..b886c4d --- /dev/null +++ b/javaProblems/problem17/Test.java @@ -0,0 +1,51 @@ +import java.util.logging.Level; +import java.util.logging.Logger; + +public class Test { + public static void main(String[] args) { + Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); + Solution solution = new Solution(); + long result; + + // Test 1 + try { + result = solution.sumPrimes(10); + } catch (Exception e) { + logger.log(Level.SEVERE, "Runtime error"); + System.exit(1); + throw new Error("Runtime Error"); + } + if (result != 17) { + logger.log(Level.SEVERE, "Wrong solution! Expected: 17, Got: " + result); + System.exit(1); + } + + // Test 2 + try { + result = solution.sumPrimes(20); + } catch (Exception e) { + logger.log(Level.SEVERE, "Runtime error"); + System.exit(1); + throw new Error("Runtime Error"); + } + if (result != 77) { + logger.log(Level.SEVERE, "Wrong solution! Expected: 77, Got: " + result); + System.exit(1); + } + + // Test 3 + try { + result = solution.sumPrimes(30); + } catch (Exception e) { + logger.log(Level.SEVERE, "Runtime error"); + System.exit(1); + throw new Error("Runtime Error"); + } + if (result != 129) { + logger.log(Level.SEVERE, "Wrong solution! Expected: 129, Got: " + result); + System.exit(1); + } + + System.out.print("All test cases passed!"); + } +}