Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Fibonacci (non recursive) panics after 47th term

I am writing a program to calculate Fibonacci series non recursively. Nothing fancy. The program runs, but panics at the 47th term, then terminates. Here’s the error:

.
.
.
count 45 - fib - 701408733
count 46 - fib - 1134903170
count 47 - fib - 1836311903
thread 'main' panicked at 'attempt to add with overflow', src\main.rs:20:23
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
error: process didn't exit successfully: `target\debug\fib.exe 50` (exit code: 101)

Up to 46, it works. So if I do cargo run 46, it work. Any number above it, it panics.

I wonder what’s wrong. Here’s the code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

fn main() {
    let args: Vec<String> = std::env::args().collect(); //Taking the range from the user

    let mut a: u32 = 0;
    let mut b: u32 = 1;
    let mut count: u32 = 0;

    let range: u32 = args[1].parse().unwrap(); // Converting input String to (unsigned) int

    if range <= 0 {
        println!("Please enter positive number greater than 0 please");
    } else if range == 1 {
        println!("{}", args[1])
    } else {
        while count < range {
            println!("count {} - fib - {}", count+1, &a);
            let nth = a + b;
            a = b;
            b = nth;
            count += 1;
        }
    }
}

>Solution :

Check the error message : panicked at 'attempt to add with overflow'
It means that your next fibonnaci number is so big that it do not fit in an u32. Would work if you use u64 or any bigger integer size.
Check the limits for each number in the documentation.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading