We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Project Euler #1: Multiples of 3 and 5
Project Euler #1: Multiples of 3 and 5
Contest ends in
Sort by
recency
|
1392 Discussions
|
Please Login in order to post a comment
Optimise solution to reduce O(n) to O(1).
sum of multiple of x = x * k * (k + 1) / 2 where, k = n - 1 / x
use this mathematical formula to sum of multiples. Instead of iterating through all numbers less than n
const sumMul = (n) => { const _mul = (x) => { const _t = BigInt(Math.floor(Number((BigInt(n) - 1n) / BigInt(x)))); return (BigInt(x) * _t * (_t + 1n)) / 2n; }; return _mul(3) + _mul(5) - _mul(3 * 5); }; function main() { var t = parseInt(readLine()); for (var a0 = 0; a0 < t; a0++) { var n = parseInt(readLine()); n >=1 && console.log(sumMul(Number(BigInt(n))).toString()); } } Use BigInt for testCase 2 and 6 for large number in javascript.
this shows time excedence how do i manage that can anyone tell me