Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

what is the difference between dirct multiplication and recursion in rust

I am new to rust and I am trying to solve this leetcode question, I wrote the following code snippet

fn main() {
    println!("{}", Solution::my_pow(0.00001, 2147483647))
}

struct Solution {}

impl Solution {
    pub fn my_pow(x: f64, n: i32) -> f64 {
        let mut base = x;
        let mut exp = n;
        let mut res = 1.0;
        if n < 0 {
            base = 1.0 / base;
            exp = -n;
        }
        let mut i = 1;
        while exp != 0 {
            let mut temp = base;
            while i * 2 <= exp {
                temp *= temp;
                i *= 2;
            }
            res *= temp;
            exp -= i;
            i = 1;
        }
        res
    }
}

when I run the code, it panicked and print an error message say thread 'main' panicked at 'attempt to multiply with overflow', src/main.rs:19:19, but the following code snippet

impl Solution {
    pub fn my_pow(x: f64, n: i32) -> f64 {
        fn pow(x: f64, res: f64, n: i64) -> f64 {
            match n {
                0 => res,
                n if n & 1 == 1 => pow(x*x, res*x, n>>1),
                _ => pow(x*x, res, n>>1)
            }
        }
        match n {
            0 => 1.0,
            n if n < 0 => pow(1.0/x, 1.0, (n as i64).abs()),
            _ => pow(x, 1.0, n as i64)
        }
    }
}

could run just as expected. I am confused. What is the difference between the two code snippets?

question from:https://stackoverflow.com/questions/65872046/what-is-the-difference-between-dirct-multiplication-and-recursion-in-rust

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What is the difference between the two code snippets?

That one of them overflows and the other not. Did you consider reading the error message and wondering how that could be relevant to your code? The panic is pointing to:

while i * 2 <= exp {

You've defined i without specifying its type, meaning it's an i32 (32b signed integer, two's complement). You keep multiplying it by 2 so aside from its initial value it can only be even, and you're doing so until it's larger than exp which is initially n and thus 2147483647.

The even number larger than 2147483647 is 2147483648, which is not a valid i32, therefore it overflows. Which is what the panic tells you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...