Recursive Fibonacci - c++

I'm having a hard time understanding why
#include <iostream>
using namespace std;
int fib(int x) {
if (x == 1) {
return 1;
} else {
return fib(x-1)+fib(x-2);
}
}
int main() {
cout << fib(5) << endl;
}
results in a segmentation fault. Once x gets down to 1 shouldn't it eventually return?

When x==2 you call fib(1) and fib(0):
return fib(2-1)+fib(2-2);
Consider what will happen when fib(0) is evaluated...

The reason is because Fibonacci sequence starts with two known entities, 0 and 1. Your code only checks for one of them (being one).
Change your code to
int fib(int x) {
if (x == 0)
return 0;
if (x == 1)
return 1;
return fib(x-1)+fib(x-2);
}
To include both 0 and 1.

Why not use iterative algorithm?
int fib(int n)
{
int a = 1, b = 1;
for (int i = 3; i <= n; i++) {
int c = a + b;
a = b;
b = c;
}
return b;
}

By definition, the first two numbers in the Fibonacci sequence are 1 and 1, or 0 and 1. Therefore, you should handle it.
#include <iostream>
using namespace std;
int Fibonacci(int);
int main(void) {
int number;
cout << "Please enter a positive integer: ";
cin >> number;
if (number < 0)
cout << "That is not a positive integer.\n";
else
cout << number << " Fibonacci is: " << Fibonacci(number) << endl;
}
int Fibonacci(int x)
{
if (x < 2){
return x;
}
return (Fibonacci (x - 1) + Fibonacci (x - 2));
}

I think this solution is short and seem looks nice:
long long fib(int n){
return n<=2?1:fib(n-1)+fib(n-2);
}
Edit : as jweyrich mentioned, true recursive function should be:
long long fib(int n){
return n<2?n:fib(n-1)+fib(n-2);
}
(because fib(0) = 0. but base on above recursive formula, fib(0) will be 1)
To understand recursion algorithm, you should draw to your paper, and the most important thing is : "Think normal as often".

This is my solution to fibonacci problem with recursion.
#include <iostream>
using namespace std;
int fibonacci(int n){
if(n<=0)
return 0;
else if(n==1 || n==2)
return 1;
else
return (fibonacci(n-1)+fibonacci(n-2));
}
int main() {
cout << fibonacci(8);
return 0;
}

int fib(int n) {
if (n == 1 || n == 2) {
return 1;
} else {
return fib(n - 1) + fib(n - 2);
}
}
in fibonacci sequence first 2 numbers always sequels to 1 then every time the value became 1 or 2 it must return 1

int fib(int x)
{
if (x == 0)
return 0;
else if (x == 1 || x == 2)
return 1;
else
return (fib(x - 1) + fib(x - 2));
}

int fib(int x)
{
if (x < 2)
return x;
else
return (fib(x - 1) + fib(x - 2));
}

if(n==1 || n==0){
return n;
}else{
return fib(n-1) + fib(n-2);
}
However, using recursion to get fibonacci number is bad practice, because function is called about 8.5 times than received number.
E.g. to get fibonacci number of 30 (1346269) - function is called 7049122 times!

My solution is:
#include <iostream>
int fib(int number);
void call_fib(void);
int main()
{
call_fib();
return 0;
}
void call_fib(void)
{
int input;
std::cout<<"enter a number\t";
std::cin>> input;
if (input <0)
{
input=0;
std::cout<<"that is not a valid input\n" ;
call_fib();
}
else
{
std::cout<<"the "<<input <<"th fibonacci number is "<<fib(input);
}
}
int fib(int x)
{
if (x==0){return 0;}
else if (x==2 || x==1)
{
return 1;
}
else if (x>0)
{
return fib(x-1)+fib(x-2);
}
else
return -1;
}
it returns fib(0)=0 and error if negitive

I think it's the best solution of fibonacci using recursion.
#include<bits/stdc++.h>
typedef unsigned long long ull;
typedef long long ll;
ull FIBO[100005];
using namespace std;
ull fibo(ull n)
{
if(n==1||n==0)
return n;
if(FIBO[n]!=0)
return FIBO[n];
FIBO[n] = (fibo(n-1)+fibo(n-2));
return FIBO[n];
}
int main()
{
for(long long i =34;i<=60;i++)
cout<<fibo(i)<<" " ;
return 0;
}

I think that all that solutions are inefficient. They require a lot of recursive calls to get the result.
unsigned fib(unsigned n) {
if(n == 0) return 0;
if(n == 1) return 1;
return fib(n-1) + fib(n-2);
}
This code requires 14 calls to get result for fib(5), 177 for fin(10) and 2.7kk for fib(30).
You should better use this approach or if you want to use recursion try this:
unsigned fib(unsigned n, unsigned prev1 = 0, unsigned prev2 = 1, int depth = 2)
{
if(n == 0) return 0;
if(n == 1) return 1;
if(depth < n) return fib(n, prev2, prev1+prev2, depth+1);
return prev1+prev2;
}
This function requires n recursive calls to calculate Fibonacci number for n. You can still use it by calling fib(10) because all other parameters have default values.

Related

Number of ways in which you can climb a staircase with 1, 2 or 3 steps - memoization

I have to calculate the number of ways one can climb a staircase taking 1, 2, or 3 steps at a time. I know of ways to do this, for example, f(n-1) + f(n-2) + f(n-3) but I would like to know why in my implementation (which is different from the above) I do not get the correct answer. I'm using a for loop instead.
The problem is every time a value is returned that is non-zero but that value includes a pre-calculated answer, and hence is not used by my code. What changes do I need to make?
#include <iostream>
#include <map>
using namespace std;
int nWays = 0;
int stepPerms(int n, map<int, int> &memo) {
if (memo.find(n) != memo.end())
return memo[n];
if (n == 0)
return 0;
if (n < 0)
return -1;
for (int i = 1; i <= 3; i++) {
int retVal = stepPerms(n - i, memo);
if (retVal == 0)
memo[n] = ++nWays;
}
return memo[n];
}
int main() {
map<int, int> memo;
cout << stepPerms(5, memo);//cout << stepPerms(3) << endl;
}
I solved it like this :
#include <iostream>
#include <map>
using namespace std;
map<int, int> memo;
int stepPerms(int n) {
if (memo.find(n) != memo.end())
return memo[n];
if (n == 0)
return 0;
if (n == 1)
return 1;
if (n == 2)
return 2;
if (n == 3)
return 4;
for (int i = 1; i <= 3; i++)
memo[n] += stepPerms(n - i);
return memo[n];
}
int main() {
cout << stepPerms(27);
}

highest power of 2 behind a number

I am writing a code to give numbers in a line and the inputs finish with zero then wirtes the highest power of 2 smaller or equal the inputs in a line.
it doesn't work.
#include<iostream>
#include<stdio.h>
using namespace std;
int highestPowerof2( int n)
{
static int result = 0;
for (static int i=n; i>=1; i--)
{
if ((i & (i-1)) == 0)
{
result = i;
break;
}
}
return result;
}
int main() {
static int num ;
do{
cin>>num ;
}
while(num=!0);
cout<<highestPowerof2(num)<<"\n";
return 0;
}
The most surprising thing in your code is this:
do{
cin>>num ;
}
while(num=!0);
You keep reading num from user input until num == 0. I have to admit that I dont really understand the rest of your code, but for num == 0 calling the function highestPowerof2(num) will always result in 0.
Perhaps you wanted to repeat the program until the user decides to quit, that could be
do{
cin>>num ;
cout<<highestPowerof2(num)<<"\n";
} while(num=!0);
PS: the other "surprising" thing is that you use static in places where it does not really make sense. Better simply remove it.
Here is another approach that is a little bit faster for large n. For example if n = 2^31 - 1, then the original loop would need to iterate 2^30 - 1 = 1,073,741,823 times, whereas this loop only needs a single iteration (provided sizeof(int) == 4):
#include <iostream>
#include <stdio.h>
using namespace std;
int highestPowerof2( int n)
{
if (n < 0) return 0;
int result = 0;
int num_bits = sizeof(int) * 8;
unsigned int i = 1 << (num_bits - 1);
while(i > 0) {
if (n >= i) return i;
i >>= 1;
}
return 0;
}
int main() {
int num ;
while (1) {
cin >> num;
cout << highestPowerof2(num) << "\n";
if (num == 0) break;
}
return 0;
}

How to check if a number is prime in a more efficient manner?

So I have the following problem. They give me an array w/ n numbers and I have to print if it contains any prime numbers using "Divide et Impera". I solved the problem but it gets only 70/100 because it isn't efficient(they say).
#include <iostream>
using namespace std;
bool isPrime(int x){
if(x == 2) return false;
for(int i = 2; i <= x/2; ++i)
if(x%i==0) return false;
return true;
}
int existaP(int a[], int li, int ls){
if(li==ls)
if(isPrime(a[li]) == true) return 1;
else return 0;
else return existaP(a, li, (li+ls)/2)+existaP(a, (li+ls)/2+1, ls);
}
int main(){
int n, a[10001];
cin >> n;
for(int i = 1; i<=n; ++i) cin >> a[i];
if(existaP(a,1,n) >= 1) cout << "Y";
else cout << "N";
return 0;
}
The lowest hanging fruit here is your stopping conditional
i <= x/2
which can be replaced with
i * i <= x
having taken care to ensure you don't overflow an int.This is because you only need to go up to the square root of x, rather than half way. Perhaps i <= x / i is better still as that avoids the overflow; albeit at the expense of a division which can be relatively costly on some platforms.
Your algorithm is also defective for x == 2 as you have the incorrect return value. It would be better if you dropped that extra test, as the ensuing loop covers it.
Here is an efficinent way to check prime number.
bool isPrime(int num) {
if(num <= 1) return false;
if (num <= 3) return true;
int range = sqrt(num);
// This is checked so that we can skip
// middle five numbers in below loop
if (num % 2 == 0 || num % 3 == 0)
return false;
for (int i = 5; i <= range; i += 6)
if (num % i == 0 || num % (i + 2) == 0)
return false;
return true;
}
A stander way(maybe..?) is just check from i = 0 to the sqrt(number)
bool isPrime(int num){
if(num == 1) return false;
for(int i = 2;i<=sqrt(num);i++){
if(num % i == 0) return false;
}
return true;
}
bool isprime(int x)
{
if(x <= 1) return false;
if(x == 2 || x == 3) return true;
if(x % 2 == 0 || x % 3 == 0) return false;
if((x - 1) % 6 != 0 && (x + 1) % 6 != 0) return false;
for(int i = 5; i * i <= x; i += 6)
{
if(x % i == 0 || x % (i + 2) == 0) return false;
}
return true;
}
If prime numbers need to be printed for a particular range or to determine whether a number is prime or not, the sieve of the eratosthenes algorithm is probably preferable as it is very efficient in terms of time complexity O( n * log2( log2(n) ) ), but the space complexity of this algorithm can cause an issue if the numbers are exceeding certain memory limit.
We can optimize this simpler algorithm which has a time complexity of O(n1/2) by introducing few additional checks based on this thoerem as shown in the above isprime code block.
Despite the fact that Sieve of Erathosthenes algorithm is efficient in terms of time complexity under space restrictions, the above provided isprime code block can be utilized, and there are numerous variations of the Sieve of Erathosthenes algorithm that perform considerably better, as explained in this link.
Many more algorithms exist, but in terms of solving coding challenges, this one is simpler and more convenient. You can learn more about them by clicking on the following links:
https://www.quora.com/Whats-the-best-algorithm-to-check-if-a-number-is-prime
https://www.baeldung.com/cs/prime-number-algorithms#:~:text=Most%20algorithms%20for%20finding%20prime,test%20or%20Miller%2DRabin%20method.
Your code will give a wrong answer if n is 1.
Your time complexity can be decreased to sqrt(n) , where n is the number.
Here is the code
bool isPrime(long int n)
{
if (n == 1)
{
return false;
}
int i = 2;
while (i*i <= n)
{
if (n % i == 0)
{
return false;
}
i += 1;
}
return true;
}
The "long int" will help to avoid overflow.
Hope this helps. :-)
If the numbers are not too big you could also try to solve this using the sieve of Eratosthenes:
#include <iostream>
#include <array>
using namespace std;
constexpr int LIMIT = 100001;
// not_prime because global variables are initialized with 0
bool not_prime[LIMIT];
void sieve() {
int i, j;
not_prime[2] = false;
for(int i = 2; i < LIMIT; ++i)
if(!not_prime[i])
for(int j = i + i; j < LIMIT; j += i)
not_prime[j] = true;
}
int existaP(int a[], int li, int ls){
if(li==ls)
if(!not_prime[a[li]] == true)
return 1;
else
return 0;
else
return existaP(a, li, (li + ls) / 2) + existaP(a, (li + ls) / 2 + 1, ls);
}
int main(){
int n, a[10001];
cin >> n;
for(int i = 1; i<=n; ++i) cin >> a[i];
sieve();
if(existaP(a,1,n) >= 1) cout << "Y";
else cout << "N";
return 0;
}
Basically when you encounter a prime all the numbers that are a multiple of it won't be primes.
P.S.: Acum am vazut ca esti roman :)
Poti sa te uiti aici pentru a optimiza si mai mult algoritmul: https://infoarena.ro/ciurul-lui-eratostene
Another inefficiency not yet mentioned is existaP(a, li, (li+ls)/2) + existaP(a, (li+ls)/2+1, ls);
In particular, the problem here is the +. If you know existaP(a, li, (li+ls)/2) > 0, then existaP(a, (li+ls)/2+1, ls) no longer matters. In other words, you're currently counting the exact number of unique factors, but as soon as you know a number has at least two factors you know it's not prime.
Here is one efficient way to check a given number is prime.
bool isprime(int n) {
if(n<=1)
return false;
if(n<=3)
return true;
if(n%2==0||n%3==0)
return false;
for(int i=5;i*i<=n;i=i+6) {
if(n%i==0||n%(i+2)==0)
return false;
}
return true;
}
This is a much faster algorithm in my opinion. It works on the Euclidean algorithm to calculate H.C.F. Basically, I check if the HCF of the number AND the consecutively second number is 1; and if the number itself is divisible by either 2 or 3. Don't ask how I mathematically reached the solution, it just struck me :D. The time complexity of this solution is O(log (max(a,b))), which is notably smaller than the time complexity of the program which runs a loop counter 2 to sqrt(n) is O(sqrt(n)).
#include <iostream>
using namespace std;
int hcf(int, int);
int hcf(int a, int b)
{
if (b == 0)
{
return a;
}
return hcf(b, a % b);
}
int main()
{
int a;
cout << "\nEnter a natural number: ";
cin >> a;
if(a<=0)
{
cout << "\nFor conventional reasons we keep the discussion of primes to natural numbers in this program:) (Read: Ring of Integers / Euclid's Lemma)";
return 0;
}
if (a == 1)
{
cout << "\nThe number is neither composite nor prime :D";
return 0;
}
if (a == 2)
{
cout << "\nThe number is the only even Prime :D";
return 0;
}
if (hcf(a, a + 2) == 1)
{
if (a % 2 != 0 && a % 3 != 0)
{
cout << "\nThe number is a Prime :D";
return 0;
}
}
cout << "\nThe number is not a Prime D:";
return 0;
}
Correct me if I'm wrong. I'm a student.

C++ Fibonacci Program

C++ Program help
Hello, I am writing a c++ program to print out several fibonacci numbers that are prime. The program prints out 8 numbers but not only those that are prime. Can some please help me find out what is going on
#include <iostream>
#include <cmath>
using namespace std;
//fibonacci function
int fibonacci(int x) {
if ((x == 1) || (x == 2)) { return 1; }
return fib(x - 1) + fib(x - 2);
}
//prime test bool function
bool is_prime(double n) {
for (int i = 2; i <= sqrt(n); i++) {
if (n % i != 0) { return true; }
else { return false; }
}
}
// main function
int main (){
int y = 1;
int c = 0;
while (y >= 0) {
fibonacci(y);
if ((is_prime(true)) && (fibonacci(y) != 1)) {
cout << fib(y) << " ";
count++;
if (c >= 8) { return 0; }
}
y++;
}
}
return 0;
}
Your code above uses double names for the function, and also you use c while you may mean count.
The is_prime function logic should take an int and the function logic is better to be rewritten to look for values that show if the number is not prime.
Lastly, using recursion with Fibonacci function is resource exhaustive. it is better to use plain loops.
check this code against yours:
#include <iostream>
#include <cmath>
using namespace std;
int fib(int x)
{
int first = 0, second = 1, sum = 0;
if ((x == 1) || (x == 2)) { return 1; }
for (int i = 2; i <= x; ++i)
{
sum = first + second;
first = second;
second = sum;
}
return sum;
}
bool is_prime(int n) // n should be int not double
{
for (int i = 2; i <= sqrt(n); i++)
if (n % i == 0)
return false; // you should look for what breaks the condition
return true; // if nothing break the condition you return true
}
int main ()
{
for (int i = 1; i <= 8; ++i)
{
int f = fib(i);
if (is_prime(f))
cout << f << " ";
}
}
Your is_prime() function has a logical problem and appears to be returning the opposite evaluation for input numbers. Try the following:
bool is_prime(int n) {
for (int i=2; i <= sqrt(n); i++) {
// if input divisible by something other than 1 and itself
// then it is NOT prime
if (n % i == 0) {
return false;
}
}
// otherwise it is prime
return true;
}
Here is a demo showing that the refactored is_prime() function is working correctly:
Rextester
Then you can use this function along with your Fibonacci number generator to find say the first 8 prime Fibonacci numbers:
int c = 0;
int y = 1;
do {
int fib = fibonacci(y);
++y;
if (is_prime(fib)) {
cout << fib << " ";
++c;
}
} while (c < 8);
As a side note, your fibonacci() function uses recursion and it won't scale well for large number inputs. Consider using dynamic programming there to dramatically improve performance.
Use Tim Biegeleisen answer for the issues in is_prime() function.
But additionally you do not check your Fibonacci number at all, is_prime is always being called with the same value is_prime(true). And apart of that, in current implementation while cycle will never finish. Try to consider following for the while loop:
while (y >= 0) {
double fib = fibonacci(y);
if ( is_prime(fib) && (fib != 1) ) {
cout << fib << " ";
c++;
if (c >= 8) { return 0; }
}
y++;
}

Fibonacci series

I am trying to do an exercise with the Fibonacci series.
I have to implement with a recursive function, a succession of the prime n number of Fibonacci and print them
in the same function. The problem is that my function print also the intermediate number.
The results, for example, for n = 6, should be : 1 1 2 3 5 8.
Any solutions?
Thanks
#include<iostream>
using namespace std;
int rec(int n)
{
int a, b;
if (n == 0 || n == 1)
{
return n;
}
else
{
a = rec(n - 1);
b = rec(n - 2);
cout << a + b << endl;
return a + b;
}
}
int main()
{
int n = 6;
rec(n);
return 0;
}
I have taken help of static int. That worked the way you wanted.
void rec(int n)
{
static int a=0,b=1,sum;
if(n>0)
{
sum = a+b;
a=b;
b= sum;
cout<<sum<<" ";
rec(n-1);
}
}
Though you have to print the first Fibonacci number yourself in main().
cout<<"0 ";
rec(n);
You can use this:
#include<iostream>
using namespace std;
#define MAXN 100
int visited[MAXN];
int rec(int n)
{
if(visited[n])
{
return visited[n];
}
int a, b;
if (n == 0|| n==1)
{
return n;
}
else
{
a = rec(n - 1);
b = rec(n - 2);
cout << " " <<a + b;
return visited[n] = a + b;
}
}
int main()
{
int n = 6;
cout<< "1";
rec(n);
cout<<endl;
return 0;
}
This implementation uses dynamic programming. So it reduces the computation time :)
Because you are printing in rec, its printing multiple times because of recursion. No need to print in the recursive function. Instead print the result in main
#include<iostream>
using namespace std;
int rec(int n)
{
int a, b;
if (n == 0 || n == 1)
{
return n;
}
else
{
a = rec(n - 1);
b = rec(n - 2);
//cout << a + b << endl;
return a + b;
}
}
int main()
{
int n = 6;
for (int i = 1; i <= n; i++)
{
cout << rec(i) << endl;
}
system("pause");
return 0;
}
I'm pretty sure you have gotten working solutions but I have a slightly different approach that doesn't require you to use data structures:
/* Author: Eric Gitangu
Date: 07/29/2015
This program spits out the fibionacci sequence for the range of 32-bit numbers
Assumption: all values are +ve ; thus unsigned int works here
*/
#include <iostream>
#include <math.h>
#define N pow(2.0,31.0)
using namespace std;
void fibionacci(unsigned int &fib, unsigned int &prevfib){
unsigned int temp = prevfib;
prevfib = fib;
fib += temp;
}
void main(){
int count = 0;
unsigned int fib = 0u, prev = 1u;
while(fib < N){
if( fib ==0 ){
fib = 0;
cout<<" "<< fib++ <<" \n ";
continue;
}
if( fib == 1 && count++ < 2 ){
fib = 1;
cout<< fib <<" \n ";
continue;
}
fibionacci(fib, prev);
cout<< fib <<" \n ";
}
}
Try this recursive function.
int fib(int n)
return n<=2 ? n : fib(n-1) + fib(n-2);
It is the most elegant solution I know.