简体   繁体   中英

Project Euler #16 on Python

import math

def sumOfDigit(num):
    sum_of_digits = 0
    while num > 9:
        sum_of_digits += num % 10
        num = int(num/10)
    sum_of_digits += num
    return sum_of_digits

print sumOfDigit(math.pow(2,1000))

This is what I thought of for Project Euler #16 , and it works fine for smaller numbers. But when I tried 2 1000 , the code gave me 1289.0 instead of the answer 1366 (Found this on the internet). I think the problem might have to do with the size of the number, but I'm not sure. Any points in the right direction will be appreciated. Thanks in advance!

Edit: Here is the question https://projecteuler.net/problem=16

The reason is that math.pow(2,1000) returns a float and not an int . Therefore, the operation num/10 returns a different answer than expected.

When calling with 2 ** 1000 the expected answer is returned.

Edit: in case of python 3, please note Hans comment or tobias_k answer regarding integers division.

The problem is that math.pow returns a floating point number, and for that large a number, the floating point precision is not good enough to give you a precise answer. Change your function like this:

def sumOfDigit(num):
    sum_of_digits = 0
    while num > 9:
        sum_of_digits += num % 10
        num = num // 10  # use integer division // instead of /
    sum_of_digits += num
    return sum_of_digits

print(sumOfDigit(pow(2, 1000))) # use builtin pow or ** operator instead of math.pow

Or shorter:

print(sum(int(c) for c in str(2**1000)))

I'd say that your number calculation is simply wrong. It can be achieved much easier:

import math

number = str(int(math.pow(2,1000)))
total = 0

for i in number:
    total += int(i)

print(total) #1366

Simply calculate the result of 2 1000 , convert it to str and go through the numbers to sum them up.

Without math module, basically can be done like this:

a=list(str(2**1000))
b=0
for i in range(0,len(a)):
b+=int(a[i])
print(b)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM