i did math problem today , first attempted in python after getting wrong answer used c#. add digits long number (2^1000). sum of these digits answer. here python script:
#! /usr/bin/env python3 n = 2**1000 count = 0 while (n > 0): count += n % 10 n = (int)(n/10) print (count) this script gives result 1189. i'm adding last digit of number count, removing number , repeating process. here similar code in c#:
//yes string same output 2^1000. had python write string file me. string str = "10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376"; int32 answer = 0; foreach (char c in str) { answer += (convert.toint32(c) - 48); } lbloutput.text = answer.tostring(); c# gives output: 1366 correct answer. i'm curious why python script gets wrong answer. looking @ math in wrong way?
just this:
n = 2 ** 1000 count = 0 while n > 0: count += n % 10 n //= 10 print(count) why code goes wrong because (int)(n/10) first converts n double, divides 10 , truncates. rounding errors made in process. in python 3.x // used integer division.
oh , finally, (int)(n / 10) bad style, don't use c-style casts in python. create int() object, use int(n / 10). error prone rounding errors, use integer division instead: n // 10. , since doing n = n // 10 can write n //= 10.
Comments
Post a Comment