From 5f017537f49d469d1b728d4323a8752cde932ab7 Mon Sep 17 00:00:00 2001 From: Jumanazar Saidov Date: Thu, 17 Aug 2023 16:50:31 +0500 Subject: [PATCH] added java solution that has O(1) time and space complexity --- solutions/015.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/solutions/015.md b/solutions/015.md index 2b2c9e6..a2655f8 100644 --- a/solutions/015.md +++ b/solutions/015.md @@ -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`.