memory - 线程 'main'对 'attempt to multiply with overflow'感到 panic

标签 memory rust

我在Rust中解决了Euler#4项目。有一行代码花了我大约30分钟的时间来解决。当我删除该行时,我得到:线程'main' panic 于'试图与溢出相乘'说明在代码中:( see on playground)
奇怪的是,rev为0,但是当我尝试时:rev = 0;在我标记为“这里有问题”的地方,即使值相同,它也可以解决问题。这是为什么?我已经检查过了,这不是重复的问题。我也不知道标题中应该写些什么,因为这是一个罕见的错误。

//Task: Find the largest palindrome made from the product of two 3-digit numbers.
    fn main(){   
        let mut pal;//palindrome
        let mut ram;//a second number that's equal to palindrome, to copy it's digits.
        let mut rev=0;//reversed palindrome
        let mut lar=0;//largest palindrome
        for ln in 100..1000{//ln=left number     }  left number * right number = palindrome
            for rn in 100..1000{//rn=right number}                                   ^
                pal=ln*rn;//                                                         |
                ram=pal;
                
                //-----------------Problem here-----------------
                //rev=ram%10;//when this line is commented, it gives:
                //thread 'main' panicked at 'attempt to multiply with overflow', why_overflow_pe4.rs:13:17
                
    
                while ram>0{//getting the last digit of ram for the first digit of rev
                            //and continuing until ram=0 and rev is reversed.
                    rev*=10;
                    ram/=10;
                    rev+=ram%10;
                }
                rev/=10;
                if pal==rev && pal>lar{//if rev=pal and our palindrome is larger than previous largest
                                      //make the largest palindrome current palindrome
                    lar=pal;
                }
            }
        }
        println!("{}",lar);
    }
-谢谢!

最佳答案

revInspecting the contents before the multiplication可能会有所帮助:rev的值为1010102010,并将其乘以10将导致rev保留的数字太大(即需要太多位)。
如果取消注释rev=ram%10rev肯定会小于10,因此将其乘以10最多得到100。
您可以使用u8u16u32u64u128等来判断数据类型的大小,但是即使u128也会溢出。因此,您既可以调整算法,也可以使用支持超过128位的数据类型。

关于memory - 线程 'main'对 'attempt to multiply with overflow'感到 panic ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63647958/

相关文章:

c - 创建线程时linux进程内存增长

linux - 如何查看按实际内存使用情况排序的顶级进程?

java - 在java中存储文本文档: memory usage

Rust 程序偶尔会给出不一致的结果

shell - 在 Rust 中简单的用户编写的 shell 中关闭 std::os::Pipe

c# - 使用 Span<T> 不进行任何分配的子字符串

Java 内存使用 - 原语

rust - 我是否必须使用 usize 来访问向量的元素?

rust - 是否可以专注于静态生命周期?

generics - Rust:对通用参数的引用不满足特征绑定(bind)