|
1 | 1 | /**
|
2 | | - * Problem 13 - Large Sum |
3 | | - * |
4 | | - * @see {@link https://projecteuler.net/problem=13} |
5 | | - * |
6 | | - * Work out the first ten digits of the sum of the given one-hundred 50-digit numbers. |
7 | | - */ |
| 2 | + * Work out the first ten digits of the sum of the following one-hundred 50-digit numbers. |
| 3 | +*/ |
8 | 4 |
|
9 | | -/** |
10 | | - * calculates the sum and returns first 10 digits. |
11 | | - * @param {String} nums |
12 | | - * @returns {Number} |
13 | | - */ |
| 5 | +export function largeSum (bignum) { |
| 6 | + const nums = [] |
| 7 | + for (let i = 0; i < bignum.length; i += 50) { |
| 8 | + nums.push(bignum.slice(i, i + 50)) |
| 9 | + } |
| 10 | + |
| 11 | + let pos = nums[0].length |
| 12 | + let ret = '' |
| 13 | + let num = 0 |
| 14 | + |
| 15 | + while (pos--) { |
| 16 | + for (let i = nums.length; i--;) { |
| 17 | + num += +nums[i].charAt(pos) |
| 18 | + } |
| 19 | + ret = num % 10 + ret |
| 20 | + num = num / 10 | 0 |
| 21 | + } |
14 | 22 |
|
15 | | -export const largeSum = (nums) => { |
16 | | - const arr = nums.split('\n') // convert to array of strings |
17 | | - let sum = 0n |
18 | | - for (const item of arr) { |
19 | | - sum += BigInt(item) |
20 | | - } // calculate the sum |
21 | | - return parseInt(sum.toString().substring(0, 10)) // convert the sum to a string and get the first 10 digits |
| 23 | + if (num > 0) { |
| 24 | + ret = num + ret |
| 25 | + } |
| 26 | + return ret.slice(0, 10) |
22 | 27 | }
|
0 commit comments