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?
>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!.