I am having a bit of problem with my assignment. The user enters X (an integer 1 <= x <= 10000). I then have to work out the power of 2 with x, add all the digits of the answer together and output it to the user. So for example if the user enters 4 is would be 2^4 = 16. 1+6 = 7. However this doesn’t work with large integers because 2^10000 is too big to store so I’m assuming I have to use an array.
I get the concept, I just have to keep doubling 2 ‘x’ times to get the answer, but I don’t know how to store it in an array and how to deal with when say 8 is doubled you get 16, with long multiplication you need carries don’t you?
Would be thankful of any help received.
So overall my question is:
- How to read the input of X. Do I
scanf("%s")and store in an array? - Once stored, how do I go about doubling (as the base will always be 2)
1.
Reading the input shouldn’t be a problem. As you know that 1 <= x <= 10000, you can read it as usual:
scanf("%d", &x);.2.
As you’re not allowed to use a bignum library, why not make one yourself? You can store a big number digit by digit in an array of
ints orchars. Start with something like this:That is, you’re storing 2^0 = 1 in the product initially. Then you can carry out the multiplication left-to-right: multiply each element of
pruductby 2, modulo 10. If a carry occurs, add that to the next element.When you’re done, find out the most significant digit searching right to left. Then reverse the digits, or just print them in reverse order. You can also use a marker to the most significant end. Whenever a carry out occurs in the most significant digit, the marker will be incremented.
The array size may be reduced by storing multiple digits per element, say, 6 digits per element. Then you’ll need to multiply each element by 2, modulo 1000000.
The code would be something like this: