18
18
#include < cinttypes> // / for uint64_t
19
19
#include < cstdio> // / for standard IO
20
20
#include < iostream> // / for IO operations
21
+ #include < cassert> // / for assert
21
22
22
23
/* *
23
24
* @brief Maximum Fibonacci number that can be computed
24
25
*
25
26
* @details
26
27
* The result after 93 cannot be stored in a `uint64_t` data type.
27
28
*/
28
- # define MAX 93
29
+ constexpr uint64_t MAX = 93 ;
29
30
30
31
/* *
31
32
* @brief Function to compute the nth Fibonacci number
@@ -39,9 +40,9 @@ uint64_t fib(uint64_t n) {
39
40
40
41
if (n <= 2 )
41
42
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" ) ;
45
46
return 0 ;
46
47
}
47
48
@@ -58,6 +59,7 @@ uint64_t fib(uint64_t n) {
58
59
* @returns void
59
60
*/
60
61
static void test () {
62
+ // Test for valid Fibonacci numbers
61
63
assert (fib (1 ) == 1 );
62
64
assert (fib (2 ) == 1 );
63
65
assert (fib (3 ) == 2 );
@@ -150,6 +152,17 @@ static void test() {
150
152
assert (fib (90 ) == 2880067194370816120 );
151
153
assert (fib (91 ) == 4660046610375530309 );
152
154
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
+
153
166
std::cout << " All Fibonacci tests have successfully passed!\n " ;
154
167
}
155
168
0 commit comments