Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions solutions/015.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,32 @@ function sumOfMultiples(n: number): number {
}
```


#### Java (with O(1) complexity solution)
```java
class Day008 {
/*
Calculate sum of multiples using arithmetic progression technique
*/
public int sumOfMultiples(int n) {
return calcArithmetic(3, n) + calcArithmetic(5, n) + calcArithmetic(7, n) + calcArithmetic(3 * 5 * 7, n)
- calcArithmetic(3 * 5, n) - calcArithmetic(3 * 7, n) - calcArithmetic(7 * 5, n);
}

/*
Return arithmetic of numbers starting from a1 with a1 difference up to num using
the formula: s = n/2 * (a1 + an) where
- a1: first term
- an: last term
- n: number of terms
*/
public int calcArithmetic(int a1, int num) {
int n = num / a1;
int an = n * a1;
return n * (a1 + an) / 2;
}
}
```
The given solution solves the problem by performing the following steps:
1. Initialize a variable `total` to 0 to keep track of the sum.
2. Iterate over the range from 1 to `n+1`.
Expand Down