aboutsummaryrefslogtreecommitdiff
path: root/challenge-079
diff options
context:
space:
mode:
authorAbigail <abigail@abigail.be>2020-09-21 18:56:57 +0200
committerAbigail <abigail@abigail.be>2020-09-21 18:56:57 +0200
commitfa07704e9e67658e76e89d0b00c9cfeb62d7aa42 (patch)
treebe98755ef17c1138d709cb44a768ca0c25b6a33f /challenge-079
parent5b410e796c910a170f80bc40c4a91b0b6f1f2edf (diff)
downloadperlweeklychallenge-club-fa07704e9e67658e76e89d0b00c9cfeb62d7aa42.tar.gz
perlweeklychallenge-club-fa07704e9e67658e76e89d0b00c9cfeb62d7aa42.tar.bz2
perlweeklychallenge-club-fa07704e9e67658e76e89d0b00c9cfeb62d7aa42.zip
Javascript solution for week 79, part 1
Diffstat (limited to 'challenge-079')
-rw-r--r--challenge-079/abigail/node/ch-1.js53
1 files changed, 53 insertions, 0 deletions
diff --git a/challenge-079/abigail/node/ch-1.js b/challenge-079/abigail/node/ch-1.js
new file mode 100644
index 0000000000..6c9ca09ace
--- /dev/null
+++ b/challenge-079/abigail/node/ch-1.js
@@ -0,0 +1,53 @@
+//
+// Challenge:
+//
+// You are given a positive number $N.
+//
+// Write a script to count the total numbrer of set bits of the binary
+// representations of all numbers from 1 to $N and return
+// $total_count_set_bit % 1000000007.
+//
+// https://perlweeklychallenge.org/blog/perl-weekly-challenge-079/
+//
+
+//
+// This is A000778 (https://oeis.org/A000788). There's a recursive formala
+// for the number of bits in the binary representation of 0 .. $N:
+//
+// bits (0) = 0
+// bits (2 * N) = bits (N) + bits (N - 1) + N
+// bits (2 * N + 1) = 2 * bits (N) + N + 1
+//
+
+//
+// Create an interface to read from STDIN
+//
+const rl = require ('readline') . createInterface ({
+ input: process . stdin,
+});
+
+//
+// Read lines of input, calculate the result, and print it.
+//
+rl . on ('line', (line) => {
+ console . log (bits (+line)); // Unary + numifies
+});
+
+
+//
+// Recursive function to calculate the results (see above).
+//
+let cache = [];
+function bits (n) {
+ if (n == 0) {
+ return 0;
+ }
+
+ if (!cache [n]) {
+ let half = Math . floor (n / 2);
+ cache [n] = bits (half) + half +
+ (n % 2 ? bits (half) + 1 : bits (half - 1));
+ }
+ return cache [n];
+}
+