aboutsummaryrefslogtreecommitdiff
path: root/challenge-079/ash/cpp
diff options
context:
space:
mode:
authorboblied <boblied@gmail.com>2020-09-28 07:51:57 -0500
committerboblied <boblied@gmail.com>2020-09-28 07:51:57 -0500
commit3e5b613182b5124d7d8d848843d20b3712c32be7 (patch)
tree2c960f1f5f91a3b7e117c4a850cadd51ce6f6335 /challenge-079/ash/cpp
parente15d009623ac7ee53f19ea395f14b0fd3737ee81 (diff)
parentaa14cbf8342e04b936f40bcc720a23a258137ecd (diff)
downloadperlweeklychallenge-club-3e5b613182b5124d7d8d848843d20b3712c32be7.tar.gz
perlweeklychallenge-club-3e5b613182b5124d7d8d848843d20b3712c32be7.tar.bz2
perlweeklychallenge-club-3e5b613182b5124d7d8d848843d20b3712c32be7.zip
Week 80 setup
Diffstat (limited to 'challenge-079/ash/cpp')
-rw-r--r--challenge-079/ash/cpp/ch-1.cpp43
1 files changed, 43 insertions, 0 deletions
diff --git a/challenge-079/ash/cpp/ch-1.cpp b/challenge-079/ash/cpp/ch-1.cpp
new file mode 100644
index 0000000000..27596b8967
--- /dev/null
+++ b/challenge-079/ash/cpp/ch-1.cpp
@@ -0,0 +1,43 @@
+/*
+ Task 1 from
+ https://perlweeklychallenge.org/blog/perl-weekly-challenge-079/
+*/
+
+#include <iostream>
+#include <sstream>
+
+using namespace std;
+
+int main(int argc, char** argv) {
+ if (argc != 2) {
+ cerr << "Usage: ./a.out 42" << endl;
+ return 1;
+ }
+
+ stringstream input(argv[1]);
+
+ int n;
+ input >> n;
+
+ int total_bits = 0;
+ int scale = 1;
+ n++;
+ while (scale <= n) {
+ int scale2 = scale << 1;
+
+ int fill_full = n / scale2;
+ int fill_frac = n % scale2;
+
+ int bits_full = fill_full * scale;
+ int bits_frac = 0;
+ if (fill_frac > scale) {
+ bits_frac = fill_frac - scale;
+ }
+
+ total_bits += bits_full + bits_frac;
+
+ scale = scale2;
+ }
+
+ cout << "There are " << total_bits << " set bits in the sequence from 1 to " << n << endl;
+}