Skip to content

Commit

Permalink
Add Solution for Summation of primes Problem (#115)
Browse files Browse the repository at this point in the history
* Create Solution.java

* Create Test.java

* Create Readme.md
  • Loading branch information
varundeepsaini authored Oct 1, 2023
1 parent 8c58fff commit 953676b
Show file tree
Hide file tree
Showing 3 changed files with 117 additions and 0 deletions.
42 changes: 42 additions & 0 deletions javaProblems/problem17/Readme.md
Original file line number Diff line number Diff line change
@@ -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.
24 changes: 24 additions & 0 deletions javaProblems/problem17/Solution.java
Original file line number Diff line number Diff line change
@@ -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;
}
}
51 changes: 51 additions & 0 deletions javaProblems/problem17/Test.java
Original file line number Diff line number Diff line change
@@ -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!");
}
}

0 comments on commit 953676b

Please sign in to comment.