This can be solved way more efficiently without using arrays or loops, if we approach it mathematically.
Let's assume:
a
b
c
d
then, clearly, a = b + c - d To find, a, we can start with finding the values of b, c and d.
a = b + c - d
To solve this, let's write find an algorithm to find the multiples of x below y.
x
y
n = Math.floor((y-1) / x)
x, 2x, 3x ... nx
s = x + 2x + 3x + ... + nx
=> s = x * (1 + 2 + 3 + ... + n )
=> s = x * n * (n + 1) / 2
Let's write a function for that,
function sumOfMultiplesBelow (x, y) { const n = Math.floor((y-1) / x); return x * n * (n + 1) / 2; } const b = sumOfMultiplesBelow(3, 1000); const c = sumOfMultiplesBelow(5, 1000); const d = sumOfMultiplesBelow(15, 1000); const a = b + c - d; console.log(a);
This way, we solve the problem in O(1) time and space complexity.
O(1)
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
This can be solved way more efficiently without using arrays or loops, if we approach it mathematically.
Let's assume:
a
b
c
d
then, clearly,
a = b + c - d
To find,
a
, we can start with finding the values ofb
,c
andd
.To solve this, let's write find an algorithm to find the multiples of
x
belowy
.x
(strictly) belowy
isn = Math.floor((y-1) / x)
x
is alwaysx
.x
belowy
form an Arithmetic Progression (AP),x, 2x, 3x ... nx
s = x + 2x + 3x + ... + nx
=> s = x * (1 + 2 + 3 + ... + n )
=> s = x * n * (n + 1) / 2
Let's write a function for that,
This way, we solve the problem in
O(1)
time and space complexity.