File tree 3 files changed +60
-0
lines changed
3 files changed +60
-0
lines changed Original file line number Diff line number Diff line change 195
195
* [ Problem013] ( https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem013.js )
196
196
* [ Problem014] ( https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem014.js )
197
197
* [ Problem015] ( https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem015.js )
198
+ * [ Problem016] ( https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem016.js )
198
199
* [ Problem020] ( https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem020.js )
199
200
* [ Problem1] ( https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem1.js )
200
201
* [ Problem10] ( https://github.com/TheAlgorithms/Javascript/blob/master/Project-Euler/Problem10.js )
Original file line number Diff line number Diff line change
1
+ /**
2
+ * Problem 16 - Power digit sum
3
+ *
4
+ * @see {@link https://projecteuler.net/problem=16 }
5
+ *
6
+ * 2¹⁵ = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
7
+ *
8
+ * What is the sum of the digits of the number 2¹⁰⁰⁰ ?
9
+ */
10
+
11
+ /**
12
+ * Returns the power digit sum of n^pow.
13
+ *
14
+ * @param {number } [n=2]
15
+ * @param {number } [pow=1000]
16
+ * @returns {number }
17
+ */
18
+ const powerDigitSum = function ( n = 2 , pow = 1000 ) {
19
+ // The idea is to consider each digit (d*10^exp) separately, right-to-left.
20
+ // digits = [units, tens, ...]
21
+
22
+ const digits = [ n ]
23
+ let p = 1
24
+
25
+ while ( ++ p <= pow ) {
26
+ let carry = 0
27
+ for ( let exp = 0 ; exp < digits . length ; exp ++ ) {
28
+ const prod = digits [ exp ] * n + carry
29
+ carry = Math . floor ( prod / 10 )
30
+ digits [ exp ] = prod % 10
31
+ }
32
+ while ( carry > 0 ) {
33
+ digits . push ( carry % 10 )
34
+ carry = Math . floor ( carry / 10 )
35
+ }
36
+ }
37
+
38
+ // (digits are reversed but we only want the sum so it doesn't matter)
39
+
40
+ return digits . reduce ( ( prev , current ) => prev + current , 0 )
41
+ }
42
+
43
+ export { powerDigitSum }
Original file line number Diff line number Diff line change
1
+ import { powerDigitSum } from '../Problem016'
2
+
3
+ describe ( 'Check Problem 16 - Power digit sum' , ( ) => {
4
+ it ( 'Power digit sum of 2^15' , ( ) => {
5
+ expect ( powerDigitSum ( 2 , 15 ) ) . toBe ( 26 )
6
+ } )
7
+
8
+ it ( 'Power digit sum of 2^1000' , ( ) => {
9
+ expect ( powerDigitSum ( ) ) . toBe ( 1366 )
10
+ expect ( powerDigitSum ( 2 , 1000 ) ) . toBe ( 1366 )
11
+ } )
12
+
13
+ it ( 'Power digit sum of 3^5000' , ( ) => {
14
+ expect ( powerDigitSum ( 3 , 5000 ) ) . toBe ( 11097 )
15
+ } )
16
+ } )
You can’t perform that action at this time.
0 commit comments