exercism

Exercism solutions.
git clone git://code.dwrz.net/exercism
Log | Files | Refs

grains.c (931B)


      1 #include "grains.h"
      2 
      3 const int NUMBER_OF_SQUARES = 64;
      4 
      5 // square returns the number of grains to be placed at the nth square.
      6 // An unsigned long long is necessary to hold the value of 2^64, which
      7 // on 64-bit is equivalent to the max value of that type (ULLONG_MAX).
      8 // square returns 0 for non-existing squares.
      9 unsigned long long square(int n) {
     10   if (n < 1 || n > NUMBER_OF_SQUARES) return 0;
     11   // A left shift of 0 leaves a number unchanged.
     12   // Otherwise, each left shift of 1 doubles the number;
     13   // i.e, 1 << 0 = 1, 1 << 1 = 2, 1 << 2 = 4, etc.
     14   // 00000001 = 1, 00000010 = 2, 000000100 = 4, etc.
     15   // There is one grain at the first square, not 2.
     16   // ∴, we subtract one from n to get the correct number of shifts.
     17   return 1ull << (n-1);
     18 }
     19 
     20 unsigned long long total() {
     21   unsigned long long n = 0;
     22   // Add up all the squares.
     23   for (int i = 1; i <= NUMBER_OF_SQUARES; i++) {
     24     n += square(i);
     25   }
     26   return n;
     27 }