|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const fs = require('fs'); |
| 4 | + |
| 5 | +process.stdin.resume(); |
| 6 | +process.stdin.setEncoding('utf-8'); |
| 7 | + |
| 8 | +let inputString = ''; |
| 9 | +let currentLine = 0; |
| 10 | + |
| 11 | +process.stdin.on('data', inputStdin => { |
| 12 | + inputString += inputStdin; |
| 13 | +}); |
| 14 | + |
| 15 | +process.stdin.on('end', _ => { |
| 16 | + inputString = inputString.replace(/\s*$/, '') |
| 17 | + .split('\n') |
| 18 | + .map(str => str.replace(/\s*$/, '')); |
| 19 | + |
| 20 | + main(); |
| 21 | +}); |
| 22 | + |
| 23 | +function readLine() { |
| 24 | + return inputString[currentLine++]; |
| 25 | +} |
| 26 | + |
| 27 | +function count(S, m, n, power) { |
| 28 | + // If n is 0 then there is 1 solution |
| 29 | + // (do not include any coin) |
| 30 | + if (n === 0) |
| 31 | + return 1; |
| 32 | + |
| 33 | + // If n is less than 0 then no |
| 34 | + // solution exists |
| 35 | + if (n < 0) |
| 36 | + return 0; |
| 37 | + |
| 38 | + // If there are no coins and n |
| 39 | + // is greater than 0, then no |
| 40 | + // solution exist |
| 41 | + if (m <= 0 && n >= 1) |
| 42 | + return 0; |
| 43 | + |
| 44 | + // count is sum of solutions (i) |
| 45 | + // including S[m-1] (ii) excluding S[m-1] |
| 46 | + return count(S, m - 1, n, power) + count(S, m - 1, n - Math.pow(S[m - 1], power), power); |
| 47 | +} |
| 48 | + |
| 49 | +// Complete the powerSum function below. |
| 50 | +function powerSum(X, N) { |
| 51 | + let m = 1; |
| 52 | + let sums = [] |
| 53 | + for (let i = 1; i < X; i++) { |
| 54 | + if (Math.pow(i, N) > X) { |
| 55 | + break; |
| 56 | + } else { |
| 57 | + sums.push(i); |
| 58 | + } |
| 59 | + } |
| 60 | + console.log(sums) |
| 61 | + return count(sums, sums.length, X, N); |
| 62 | +} |
| 63 | + |
| 64 | +function main() { |
| 65 | + const ws = fs.createWriteStream(process.env.OUTPUT_PATH); |
| 66 | + |
| 67 | + const X = parseInt(readLine(), 10); |
| 68 | + |
| 69 | + const N = parseInt(readLine(), 10); |
| 70 | + |
| 71 | + let result = powerSum(X, N); |
| 72 | + |
| 73 | + ws.write(result + "\n"); |
| 74 | + |
| 75 | + ws.end(); |
| 76 | +} |
0 commit comments