Think about an array that has 64 elements , write a code to insert on the first element the number 1, then double this number 1*2 =2 and store it as the second element , double the second element (2 *2 = 4) and store it as the third element, and continue this up to 63 times (n -1) and print the final product.
For example: 9,223,372,036,854,775,808
thanks for all the help
this is what I got so far
what am I doing wrong
is there a easier way then what I am doing please tell me thanks
I don't know why I keep getting zeros near the end can someone check
1 void doubleThis(int num, int until) {
2 if (until == 0) {
3 return;
4 }
5 num = num * 2;
6 cout << num << endl;
7 doubleThis(num, until-1);
8 }
9
10
11 int main() {
12 int x;
13 cout << "Enter the the number to be doubled for next 5 times " << endl;
14 cin >> x;
15 cout << "Entered number is " << x << endl;
16 doubleThis(x, 5);
17
18 return 0;
19 }
Integers only take up a certain small number of bits. On my system, for instance, int is 32 bits, which gives it a range of roughly +/- 2147 million. Chances are this is the same for you, unless you're using an out-of-date system or compiler, or are not working on a common desktop or laptop.
Note that 2^63 requires at least 63 bits to store. So 32 bits is not going to cut it. Chances are that you're experiencing signed integer overflow, which is undefined behavior. (Unsigned integer overflow wraps to zero, and is well-defined, so we'll prefer unsigned in cases where overflow is possible.)
You need any integer that is at least 64 bits in size; ask for it. uint_least64_t
#include <iostream>
usingnamespace std;
constint MAXSIZE = 100;
void doubleIt( int *a, int &last )
{
int i = 0;
int carry = 0;
while ( i <= last )
{
a[i] = 2 * a[i] + carry;
carry = a[i] / 10;
a[i] = a[i] - 10 * carry;
i++;
}
if ( carry > 0 )
{
last++;
a[last] = carry;
}
}
int main()
{
int a[MAXSIZE] = { 0 };
int last = 0;
a[0] = 1;
for ( int n = 1; n <= 128 ; n++ )
{
doubleIt( a, last );
cout << "2 to the power of " << n << " is ";
for ( int i = last; i >= 0; i-- ) cout << a[i];
cout << endl;
}
}
Gunner funner your code that you did is almost what I was looking for
is there a way I can promp the user to type a number and then that number is doubled 64 times and at the end print the final number which is 4611686018427387904
OP: you'd have to do a bit of work yourself and adapt lastchance's code to your specific needs, don't expect everything on a plate. That program has all you need