Reputation: 33
I'd like to print an large integer without the "e+XX" at the end in Python.
For example, when I write:
n = 100
k = 18
result = 1
i = 0
while i < k:
result = result * (n - i) / (i + 1)
i += 1
The result is 3.066451080298821e+19, and I would like to have 30664510802988208300.
Upvotes: 2
Views: 4941
Reputation: 15777
I think the question you really want to ask is 'how can I print a number in Python without scientific notation?'
The answer is, your number right now is a float. Try print(type(result))
and you will see it says float
. You could type cast it to an integer by doing int(result)
, and it will show close to the full number, 30664510802988208128
. It will be a bit off because of the memory size storage limitations of int vs float.
The better way to do this would be like:
result = 1
i = 0
while i < 18:
result = result * (100 - i) // (i + 1)
i += 1
print(result)
which will keep result
as an int type. It now should print 30664510802988208300
Upvotes: 2
Reputation: 213298
If you want an integer, you have to use integer division, //
instead of /
, as mentioned in @farsil's deleted answer.
result = 1
k = 18
n = 100
for i in range(k):
result = result * (n - i) // (i + 1)
print(result)
This only gives the correct result if i + 1
is always a divisor of result * (n - i)
. However, this is always true, so we are fine.
You cannot use /
because that will perform floating-point division, which will truncate the results to 56 bits. The correct result does not fit in 56 bits:
In [1]: int(float(30664510802988208300))
Out[1]: 30664510802988208128
# ^^^ oops... off by 172
In this case, when the division by 2 is performed, we have multiplied result
by n and n-1, at least one of which is a multiple of 2. When i+1 is 3, then we have multiplied by n, n-1, and n-2, at least one of which is a multiple of 3. This pattern works for all numbers.
Upvotes: 3