Skip to content

Commit c85115f

Browse files
authored
Update fibonacci_fast.cpp to meet the revision suggestions.
1 parent 0992573 commit c85115f

File tree

1 file changed

+17
-4
lines changed

1 file changed

+17
-4
lines changed

math/fibonacci_fast.cpp

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,14 +18,15 @@
1818
#include <cinttypes> /// for uint64_t
1919
#include <cstdio> /// for standard IO
2020
#include <iostream> /// for IO operations
21+
#include <cassert> /// for assert
2122

2223
/**
2324
* @brief Maximum Fibonacci number that can be computed
2425
*
2526
* @details
2627
* The result after 93 cannot be stored in a `uint64_t` data type.
2728
*/
28-
#define MAX 93
29+
constexpr uint64_t MAX = 93;
2930

3031
/**
3132
* @brief Function to compute the nth Fibonacci number
@@ -39,9 +40,9 @@ uint64_t fib(uint64_t n) {
3940

4041
if (n <= 2)
4142
return f2;
42-
if (n >= 93) {
43-
std::cerr
44-
<< "Cannot compute for n>93 due to limit of 64-bit integers\n";
43+
if (n >= MAX) {
44+
throw std::invalid_argument("Cannot compute for n>=" + std::to_string(MAX) +
45+
" due to limit of 64-bit integers");
4546
return 0;
4647
}
4748

@@ -58,6 +59,7 @@ uint64_t fib(uint64_t n) {
5859
* @returns void
5960
*/
6061
static void test() {
62+
// Test for valid Fibonacci numbers
6163
assert(fib(1) == 1);
6264
assert(fib(2) == 1);
6365
assert(fib(3) == 2);
@@ -150,6 +152,17 @@ static void test() {
150152
assert(fib(90) == 2880067194370816120);
151153
assert(fib(91) == 4660046610375530309);
152154
assert(fib(92) == 7540113804746346429);
155+
156+
// Test for invalid Fibonacci numbers
157+
try {
158+
fib(MAX + 1);
159+
assert(false && "Expected an invalid_argument exception to be thrown");
160+
} catch (const std::invalid_argument& e) {
161+
const std::string expected_message = "Cannot compute for n>=" + std::to_string(MAX) +
162+
" due to limit of 64-bit integers";
163+
assert(e.what() == expected_message);
164+
}
165+
153166
std::cout << "All Fibonacci tests have successfully passed!\n";
154167
}
155168

0 commit comments

Comments
 (0)