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

Why does this same algorithm produce completely different results in python and rust?

I’ve correctly completed problem 53 from the project euler site in python.

from math import factorial

count = 0

for n in range(1, 101):

    for r in range(0, n+1):
        val = factorial(n)/(factorial(r)*factorial(n-r))

        if val > 1_000_000:
            count += 1

print(count)

But for some reason what appears to be the exact same algorithm in rust produces an entirely different (and incorrect) answer.

fn factorial(num: u128) -> u128 {
    match num {
        0  => 1,
        1.. => (1..num+1).product(),
    }
}

fn main() {

    let mut count = 0;
    
    for n in 1..101{
    
        for r in 0..n+1{
            let val = factorial(n)/(factorial(r)*factorial(n-r));
    
            if val > 1_000_000 {
                count += 1;
            }

        }
    }
    println!("{}", count);

}

I’m not sure what I’m doing wrong and I’m sure it’s something obvious missing. Whats the difference between the two algorithms?

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

>Solution :

Integers in Python 3 are virtually unlimited. Whereas in Rust, you are hitting an overflow. The largest of the standard integer types in Rust is u128, but it’s not large enough to represent numbers as huge as 100!.

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