Suliman
1
Could anybody help to convert next code to idiomatic Rust code?
#include "stdafx.h"
#include <iostream>
using namespace std;
int main(void) {
long r = 0;
for (int i = 0; i < 10000; i++) {
for (int j = 0; j < 10000; j++) {
r = (r + (i * j) % 100) % 47;
}
}
cout << "answer: " << r << endl;
}
1 Like
mdinger
2
I think this is the same. Didn't run your C++ code. Answer supposed to be 39
?
fn main() {
let count = 10_000;
let mut r = 0;
for i in 0..count {
for j in 0..count {
r = (r + (i * j) % 100) % 47;
}
}
println!("{:?}", r);
}
playpen
1 Like
Or, if you like functional programming:
fn main() {
let r = (0..10_000).fold(0, |r, i| {
(0..10_000).fold(r, |r, j| {
(r + (i * j) % 100) % 47
})
});
println!("answer: {}", r);
}
And if you are willing to use an external library and risk an integer overflow...
#[macro_use]
extern crate itertools;
use std::iter::AdditiveIterator;
fn main() {
let r = iproduct!(0..10_000, 0..10_000).map(|(i, j)| {
(i * j) % 100
}).sum() % 47;
println!("answer: {}", r);
}
1 Like