Project Euler 1: Multiples of 3 and 5 Solution

1// O(N)
2const solution = () => {
3 const N = 1000
4 let res = 0
5 for (let i = 1; i < N; i++) {
6 if (i % 3 === 0 || i % 5 === 0) {
7 res += i
8 }
9 }
10 console.log(res)
11}
12
13// O(1)
14// Ref for formular: https://math.stackexchange.com/a/9305
15const solution2 = () => {
16 const N = 1000
17
18 const sumDivisibleBy = x => {
19 const n = Math.floor((N - 1) / x)
20 return (x * (n * (n + 1))) / 2
21 }
22
23 const res = sumDivisibleBy(3) + sumDivisibleBy(5) - sumDivisibleBy(15)
24
25 console.log(res)
26}
27
28solution()
29solution2()

Comments

Loading comments...

Tags

projecteuler

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Binary Trees With Factors

Mar 14, 2021

Previous Post

HoningJS

Search Posts