我有一个程序,对于所有小于或等于输入值的整数,它可以找到可以表示为两个立方体之和的数字,两次,也就是Ramanujan的数字问题。
我已经用Java和Rust编写了这篇文章,但是,与Java相比,它在Rust中运行的速度慢了两倍多。
我能做些什么来使它表现得更好,或者改进它吗?
rust eclipse 代码:
use num_integer::Roots;
fn main() {
let v = 984067;
// let v = 87539319;
for i in 1..=v {
ramanujan(i)
}
}
fn ramanujan(m: i32) {
let maxcube = m.cbrt();
let mut res1 = 0;
let mut res2 = 0;
let mut _res3 = 0;
let mut _res4 = 0;
for i in 1..=maxcube {
for j in 1..=maxcube {
if i * i * i + j * j * j == m {
res1 = i;
res2 = j;
break;
}
}
}
for k in 1..=maxcube {
for l in 1..=maxcube {
if k == res1 || k == res2 || l == res1 || l == res2 {
continue;
}
if k * k * k + l * l * l == m {
_res3 = k;
_res4 = l;
break;
}
}
}
// if ((res1 * res1 * res1) + (res2 * res2 * res2) == m) && ((res3 * res3 * res3) + (res4 * res4 * res4) == m) {
// println!("{} is representable as the sums of two different sets of two cubes!\nThese values are {}, {}, and {}, {}.", m, res1, res2, res3, res4);
// }
}
Java代码:
public class Ramun {
public static void main(String[] args) {
int v = 984067;
// int v = 87539319;
for (int i = 1; i <= v; i++) {
ramanujan(i);
}
}
public static void ramanujan(int m) {
int maxcube = (int) Math.round(Math.cbrt(m));
int res1 = 0, res2 = 0, res3 = 0, res4 = 0;
for (int i = 1; i <= maxcube; i++) {
for (int j = 1; j <= maxcube; j++) {
if (((i * i * i) + (j * j * j)) == m) {
res1 = i;
res2 = j;
break;
}
}
}
for (int k = 1; k <= maxcube; k++) {
for (int l = 1; l <= maxcube; l++) {
if (k == res1 || k == res2 || l == res1 || l == res2)
continue;
if (((k * k * k) + (l * l * l)) == m) {
res3 = k;
res4 = l;
break;
}
}
}
// if (((res1 * res1 * res1) + (res2 * res2 * res2) == m) && ((res3 * res3 * res3) + (res4 * res4 * res4) == m)) {
// System.out.printf("%d is representable as the sums of two different sets of two cubes!%nThese values are %d, %d, and %d, %d.%n", m, res1, res2, res3, res4);
// }
}
}
1条答案
按热度按时间6kkfgxo01#
问题在于
RangeInclusive
,它可能很昂贵。下面是一个避免这种情况的版本:
结果:
我在#45222中添加了一条注解,以引起对此问题的注意。
看起来
for_each()
也允许更好的性能(因为for
循环更自然,应该具有相同的性能,应该将其视为一个bug):一个二个一个一个