FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
C-Plus-Plus/others/fibonacci.cpp at master · SelfCodeLearning/C-Plus-Plus · GitHub
Uh oh!
There was an error while loading.
Please reload this page
.
SelfCodeLearning
/
C-Plus-Plus
Public
forked from
TheAlgorithms/C-Plus-Plus
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
C-Plus-Plus
/
others
/
fibonacci.cpp
Copy path
More file actions
More file actions
Latest commit
History
History
History
42 lines (33 loc) · 1.19 KB
Breadcrumbs
C-Plus-Plus
/
others
/
fibonacci.cpp
Copy path
File metadata and controls
42 lines (33 loc) · 1.19 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
//
An efficient way to calculate nth fibonacci number faster and simpler than O(nlogn) method of matrix exponentiation
//
This works by using both recursion and dynamic programming.
//
as 93rd fibonacci exceeds 19 digits, which cannot be stored in a single long long variable, we can only use it till 92nd fibonacci
//
we can use it for 10000th fibonacci etc, if we implement bigintegers.
//
This algorithm works with the fact that nth fibonacci can easily found if we have already found n/2th or (n+1)/2th fibonacci
//
It is a property of fibonacci similar to matrix exponentiation.
#
include
<
iostream
>
#
include
<
cstdio
>
using
namespace
std
;
const
long
long
MAX
=
93
;
long
long
f[
MAX
] = {
0
};
long
long
fib
(
long
long
n)
{
if
(n ==
0
)
return
0
;
if
(n ==
1
|| n ==
2
)
return
(f[n] =
1
);
if
(f[n])
return
f[n];
long
long
k = (n %
2
!=
0
) ? (n +
1
) /
2
: n /
2
;
f[n] = (n %
2
!=
0
) ? (
fib
(k) *
fib
(k) +
fib
(k -
1
) *
fib
(k -
1
))
: (
2
*
fib
(k -
1
) +
fib
(k)) *
fib
(k);
return
f[n];
}
int
main
()
{
//
Main Function
for
(
long
long
i =
1
; i <
93
; i++)
{
cout << i <<
"
th fibonacci number is
"
<<
fib
(i) <<
"
\n
"
;
}
return
0
;
}
Back
|
FazBrowse Home
|
New Git URL