简体   繁体   English

"<i>Can compilers (specifically rustc) really simplify triangle-summation to avoid a loop?<\/i>编译器(特别是 rustc)真的可以简化三角求和以避免循环吗?<\/b> <i>How?<\/i>如何?<\/b>"

[英]Can compilers (specifically rustc) really simplify triangle-summation to avoid a loop? How?

On page 322 of Programming Rust by Blandy and Orendorff is this claim:在 Blandy 和 Orendorff 的Programming Rust第 322 页上是这样的声明:

...Rust...recognizes that there's a simpler way to sum the numbers from one to n : the sum is always equal to n * (n+1) / 2 . ...Rust...认识到有一种更简单的方法可以将数字从 1 加到n :总和始终等于n * (n+1) / 2

This is of course a fairly well-known equivalence, but how does the compiler recognize it?这当然是一个众所周知的等价,但是编译器是如何识别它的呢? I'm guessing it's in an LLVM optimization pass, but is LLVM somehow deriving the equivalence from first principles, or does it just have some set of "common loop computations" that can be simplified to arithmetic operations?我猜它是在 LLVM 优化过程中,但是 LLVM 是否以某种方式从第一原理推导出等价,或者它只是有一些可以简化为算术运算的“公共循环计算”?

First of all, let's demonstrate that this actually happens.首先,让我们证明这确实发生了。

Starting with this code:从此代码开始:

pub fn sum(start: i32, end: i32) -> i32 {
    let mut result = 0;
    for i in start..end {
        result += i;
    }
    return result;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM