Skip to content

Commit 9524f16

Browse files
authored
fix: Add overflow protection to Fibonacci implementation (#371)
* Update fib.rs * Update fib.rs
1 parent 55a145b commit 9524f16

File tree

1 file changed

+15
-6
lines changed

1 file changed

+15
-6
lines changed

tests/integration-tests/fib.rs

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,26 @@
33
#[nexus_rt::main]
44
#[nexus_rt::public_input(n)]
55
fn main(n: u32) -> u32 {
6-
let mut a = 0;
7-
let mut b = 1;
8-
6+
// Handle edge cases
97
if n == 0 {
10-
return a;
8+
return 0;
9+
}
10+
if n == 1 {
11+
return 1;
1112
}
1213

14+
let mut a = 0u32;
15+
let mut b = 1u32;
16+
1317
for _ in 2..n {
14-
let c = a + b;
18+
// Check for potential overflow before addition
19+
if let Some(c) = a.checked_add(b) {
1520
a = b;
16-
b = c;
21+
b = c;
22+
} else {
23+
// In case of overflow, return max value
24+
return u32::MAX;
25+
}
1726
}
1827

1928
b

0 commit comments

Comments
 (0)