aboutsummaryrefslogtreecommitdiff
path: root/grains/src/lib.rs
diff options
context:
space:
mode:
authorFederico I <git@federicoigne.com>2020-03-18 17:56:11 +0000
committerFederico Igne <git@federicoigne.com>2021-11-03 18:54:52 +0000
commit204318ac52453b7d365cf0cd60c3fbeaacf4edaa (patch)
tree50e4b0756dc51e6227d884f800701454a481f305 /grains/src/lib.rs
parent581450f9b2bfba9d9ff9efdab6776b0d4fdbae14 (diff)
downloadexercism-204318ac52453b7d365cf0cd60c3fbeaacf4edaa.tar.gz
exercism-204318ac52453b7d365cf0cd60c3fbeaacf4edaa.zip
[rust] Grains
Diffstat (limited to 'grains/src/lib.rs')
-rw-r--r--grains/src/lib.rs23
1 files changed, 23 insertions, 0 deletions
diff --git a/grains/src/lib.rs b/grains/src/lib.rs
new file mode 100644
index 0000000..05449be
--- /dev/null
+++ b/grains/src/lib.rs
@@ -0,0 +1,23 @@
1pub fn square(s: u32) -> u64 {
2 assert!(s > 0 && s < 65,"Square must be between 1 and 64");
3 2_u64.pow(s-1)
4}
5
6/// This version uses the already defined `square(s)` function.
7///
8/// There is also a faster way to compute this according to
9/// [Wolfram|Alpha](https://www.wolframalpha.com/input/?i=sum_0%5En+2%5En)
10///
11/// 2_u64.pow(65) - 1 == 18_446_744_073_709_551_615
12///
13/// this solution however doesn't work because
14///
15/// 2_u64.pow(65) == 18_446_744_073_709_551_616
16///
17/// which overflows since
18///
19/// std::u64::MAX == 18_446_744_073_709_551_615
20///
21pub fn total() -> u64 {
22 (1..65).map(square).sum() // std::u64::MAX
23}