aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAbigail <abigail@abigail.be>2020-09-22 19:10:12 +0200
committerAbigail <abigail@abigail.be>2020-09-22 19:14:20 +0200
commit2810b0198d250e761bd59b12ae4756e608a0af36 (patch)
tree7ad804ecdcb2aba82d50a67743733bb1a5378be3
parent48bce165371e39ab23aee7b7b6c1cbd4c9575dbe (diff)
downloadperlweeklychallenge-club-2810b0198d250e761bd59b12ae4756e608a0af36.tar.gz
perlweeklychallenge-club-2810b0198d250e761bd59b12ae4756e608a0af36.tar.bz2
perlweeklychallenge-club-2810b0198d250e761bd59b12ae4756e608a0af36.zip
bc solution for week-079, part 1
-rw-r--r--challenge-079/abigail/bc/ch-1.bc37
1 files changed, 37 insertions, 0 deletions
diff --git a/challenge-079/abigail/bc/ch-1.bc b/challenge-079/abigail/bc/ch-1.bc
new file mode 100644
index 0000000000..bd708a7df8
--- /dev/null
+++ b/challenge-079/abigail/bc/ch-1.bc
@@ -0,0 +1,37 @@
+#
+# 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
+#
+
+bignum = 1000000007;
+
+define f(nn) {
+ auto n;
+ if (nn == 0) {return (0);}
+ if (nn % 2 == 1) {
+ n = (nn - 1) / 2;
+ return 2 * f(n) + n + 1;
+ }
+ n = nn / 2;
+ return f(n) + f(n - 1) + n;
+}
+
+define main(n) {
+ return f(n) % bignum;
+}