Power 10**10 gives the wrong output. what could be the reason?

A trainee of mine made this short python script for a problem from Project Euler.

We are using Python 3.9.4

Problem: The series, 11 + 22 + 33 + ... + 1010 = 10405071317. Find the last ten digits of the series, 11 + 22 + 33 + ... + 10001000.

It isn't the best solution but in theory it should work for small values(I know it wont work for bigger values to inefficient and even double is too small.

Here is her Code:

import math
import numpy as np
x = np.arange(1,11)
a=[]

for y in x:
     z = y**y
     a.append(z)

b=sum(a)
print(a)

Output:

[1, 4, 27, 256, 3125, 46656, 823543, 16777216, 387420489, 1410065408]

The script isn't finished yet obviously but you can see that every power 11, 22, 33 are correct up to 1010 which does not return the correct value.

Do you see any reason for this problem it seem quite odd to me? I could not figure it out.

Yes I know this isn't the best solution and in the end the actually solution will be different but it would still be nice to solve this mystery.

Upvotes: 2

Views: 398

Answers (2)

iBug
iBug

Reputation: 37257

You're probably on some kind of 32-bit systems where numpy defaults to 32-bit integers. This caused the result to be "truncated" to 32 bits. You can verify the result with the following expression:

(10 ** 10) % (2 ** 32)

Use Python built-in int and range unless you need the fancy stuff numpy provides. It's an arbitrary-precision integer implementation and should work for all kinds of integer calculation workload.

Upvotes: 7

Kraigolas
Kraigolas

Reputation: 5580

The simple solution is to not use numpy unnecessarily. The built-in range works very well:

import math

a=[]

for y in range(1, 11):
     z = y**y
     a.append(z)

b=sum(a)
print(a)
print(b)

In your case, numpy was using 32 bit integers, which overflowed when they reached their maximum value.

Upvotes: 2

Related Questions