GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — JavaScript/Project-Euler/Problem016.js at master · TheAlgorithms/JavaScript

Expand file tree

/

Problem016.js

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
43 lines (37 loc) · 1.01 KB
/

Problem016.js

Copy path

File metadata and controls

43 lines (37 loc) · 1.01 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
* Problem 16 - Power digit sum
*
* @see {@link https://projecteuler.net/problem=16}
*
* 2¹⁵ = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
*
* What is the sum of the digits of the number 2¹⁰⁰⁰ ?
*/
/**
* Returns the power digit sum of n^pow.
*
* @param {number} [n=2]
* @param {number} [pow=1000]
* @returns {number}
*/
const powerDigitSum = function (n = 2, pow = 1000) {
// The idea is to consider each digit (d*10^exp) separately, right-to-left.
// digits = [units, tens, ...]
const digits = [n]
let p = 1
while (++p <= pow) {
let carry = 0
for (let exp = 0; exp < digits.length; exp++) {
const prod = digits[exp] * n + carry
carry = Math.floor(prod / 10)
digits[exp] = prod % 10
}
while (carry > 0) {
digits.push(carry % 10)
carry = Math.floor(carry / 10)
}
}
// (digits are reversed but we only want the sum so it doesn't matter)
return digits.reduce((prev, current) => prev + current, 0)
}
export { powerDigitSum }
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.