Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to avoid number converting to the float after division in python?

I was doing codewars Super Coordinate Sums task.

def super_sum(d, n):
        return int((n - 1) * d / 2) * n ** d

This is code that i wrote. It works for like 80% of test cases, but not for those for whom d is odd and n is even. I understand that it happens because of int rounding .5, but i don’t know how to fix it. If i add type casting after multiplying:

def super_sum(d, n):
        return int((n - 1) * d / 2 * n ** d)

then float will round my answer, for example for case d = 129, n = 48 correct answer is

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

23002614121650859314295390023813765770686356346056100481311369183953951296168089825445052658029739568132862213799732717600222459651283221457666925117931656542314825567044097809172099767486211518264294073783841553301635072

but this func returns

23002614121650859002030052273414603134163824126554165855078156468894052419381420649026479480486503703631607262290068194388824847849384465650476706583375518509855234415574540876562931392494985340953010221803338452965523456

So can someone help me with it? Thank you in advance.

>Solution :

Do // 2 last.

def super_sum(d, n):
    return (n - 1) * d * n ** d // 2
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading