1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
|
/* 016.cpp
Project Euler -- Problem 16
Copyright (c) 2011 Michael Thomas Greer
Distributed under the Boost Software License, Version 1.0.
(See http://www.boost.org/LICENSE_1_0.txt )
+------------------------------------------------------------------------+
| 2^(15) = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. |
| |
| What is the sum of the digits of the number 2^(1000)? |
+------------------------------------------------------------------------+
*/
#include <algorithm>
#include <functional>
#include <iostream>
#include <iterator>
#include <numeric>
#include <vector>
using namespace std;
typedef vector <char> bignum;
char carry( char curr, char prev )
{
return curr + (prev / 10);
}
bignum& operator *= ( bignum& n, char k ) // k == single digit: 0..9
{
transform( n.begin(), n.end(), n.begin(), bind2nd( multiplies <char> (), k ) );
if (n.back() > 9)
n.push_back( 0 );
adjacent_difference( n.begin(), n.end(), n.begin(), ptr_fun( &carry ) );
transform( n.begin(), n.end(), n.begin(), bind2nd( modulus <char> (), 10 ) );
return n;
}
int main()
{
bignum n;
// Calculate 2**1000
n.push_back( 2 );
for (unsigned cntr = 1; cntr < 1000; cntr++)
n *= 2;
// Get the sum of the digits
size_t sum_of_digits = accumulate( n.begin(), n.end(), (size_t)0 );
// Turn the number into something that can be displayed...
transform( n.begin(), n.end(), n.begin(), bind2nd( plus <char> (), '0' ) );
// ...and display the results
cout << "2**1000 is ";
copy( n.rbegin(), n.rend(), ostream_iterator <char> ( cout, "" ) );
cout << "\nThe sum of the digits is " << sum_of_digits << "\n";
return 0;
}
// end 016.cpp
|