-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoin_counting.js
More file actions
49 lines (39 loc) · 1.29 KB
/
Copy pathcoin_counting.js
File metadata and controls
49 lines (39 loc) · 1.29 KB
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
44
45
46
47
48
49
/*
The coin-counting approach central metaphor begins with
suspending common usage and
assuming "coins" face values are denominated by the
polynomial solutions to the
proposed problem's answer space.
*/
// usage: node coin_counter.js <p(x)> <x>
const args = process.argv.slice(2);
let p_of_x = Number(args[0]); // p(x)
let x = Number(args[1]); // x
const coins = {0:1};
let coin_ndx = 0;
// compute the values of coins to add to purse total
// exit loop when coin face value is too large to subtract from purse
for (let n = 0; Math.pow(x, n) <= p_of_x; n++, coin_ndx++) {
coins[coin_ndx] = Math.pow(x, n); // compute coin face values
}
console.log("Show face values of coins:");
let keys = Object.keys(coins);
keys.sort();
// find the largest exponent (max_key)
let max_key = 0;
for (let key in keys) {
console.log(key, coins[key]);
// max_key = key > max_key ? key : max_key; // use current largest
max_key = key;
}
console.log("Show polynomial");
let purse = p_of_x; // purse is sum of coins
for (max_key; max_key >= 0; max_key--) {
let count = 0;
while (coins[max_key] <= purse) {
//console.log(purse, coins[max_key]);
purse -= coins[max_key];
count++;
}
console.log("+" + count + " x**" + max_key);
}