3

I am trying to print a very large number by calculating very large powers of an integer. Although my code is correct, i am not observing the desired output.

Generally, python interpreter can print very large integer as much as the system memory supports. With that assumption in mind below is the code i am running.

a = int(input())
b = int(input())
c = int(input())
d = int(input())

import math
if a in range(1,1001):
    if b in range(1,1001):
        if c in range(1,1001):
            if d in range(1,1001):
                print((math.pow(a,b)+math.pow(c,d)))

The output which i am observing is

4710194409608608302099333120

The output which is expected is

4710194409608608369201743232

Can you please provide me pointers to how this can be solved? Input Values are:

a = 9
b = 29
c = 7
d = 27
csvraju
  • 95
  • 1
  • 1
  • 5
  • 2
    @ggorlen or: `1 <= a <= 1000` – Klaus D. Sep 05 '19 at 23:38
  • 3
    @ggorlen I don't think that your claim that the range checks are linear is true. See [Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?](https://stackoverflow.com/q/30081275/4996248) – John Coleman Sep 05 '19 at 23:48
  • 1
    @ggorlen absolutely not true, `range` objects are not iterators, they are sequence-like containers that support constant time membership testing for `int` objects – juanpa.arrivillaga Sep 06 '19 at 01:23
  • Thanks, I learned something new--not sure how I missed that thread. Further reinforcement that I forget the intuitive stuff in Python. – ggorlen Sep 06 '19 at 01:34

3 Answers3

5

You are running into the limits of floating point precision. From the documentation:

Unlike the built-in ** operator, math.pow() converts both its arguments to type float. Use ** or the built-in pow() function for computing exact integer powers.

So just use **

>> 9**29+7**27
4710194409608608369201743232
Deepstop
  • 3,076
  • 2
  • 5
  • 19
5

math.pow converts the inputs to float

The expected result you are showing is the result you get when you do:

x = 9**29
y = 7**27
print(x+y)

The result you are seeing comes from this:

x = float(9**29)
y = float(7**27)
print(int(x+y))
JacobIRR
  • 6,814
  • 6
  • 30
  • 50
1

try it like this

>>> 9 ** 29 + 7 ** 27
4710194409608608369201743232