Printing 1 to n using Fibonacci recursion [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I want to print Fibonacci series from 1 to n in my function.
I know that I can do it by writing a regular Fibonacci and using it in a for block to print 1 to N. Like this:
#include <iostream>
using namespace std;
int fibo(int);
int main(){
for (int i = 0; i < 5; i++)
cout << fibo(5);
system("pause");
return 0;
}
int fibo(int n){
if (n == 1 || n == 2)
return 1;
else
return fibo(n - 1) + fibo(n - 2);
}
but my problme is that I can't do it without for,IN my function
I mean I want to Print it with a recursive algorithm
Here is my code up to now
#include <iostream>
using namespace std;
int fibo(int, bool);
int main(){
fibo(5, false);
system("pause");
return 0;
}
int fibo(int n, bool IsPrinted){
if (n == 1 || n == 2){
if (!IsPrinted)
cout << 1 << endl;
return 1;
}
else{
int temp = fibo(n - 1, IsPrinted) + fibo(n - 2, IsPrinted);
if (!IsPrinted){
cout << temp << endl;
IsPrinted = true;
}
return temp;
}
}

long fibo(int N, bool print) {
long value = 0;
if(1 == N)
value = 1;
if(1 < N)
value = fibo(N-1, print) + fibo(N-2, false);
if(print)
std::cout << N << " => " << value << std::endl;
return value;
}
int main(){
fibo(5, true);
return 0;
}
What you should realize is that the calls to the fibo function makes a tree. The root of the tree is the call to fibo(5, true) in the main(). As you only want to print each value once, the solution is to decide to print the value of the function only on the leftmost branch of that tree. The rule is then simply:
never print when on a right branch (hence the call to fibo(N-2, false)
never print if the parent didn't print (to avoid printing when on a child left branch of a right branch)

A common solution is to use memoization:
int fibo(int n)
{
static std::map<int,int> memo;
auto it=memo.find(n);
if(it!=std::end(memo))
{
return it->second;
}
int ret=1;
if (n > 2)
{
ret = fibo(n - 1) + fibo(n - 2);
}
memo[n]=ret;
return ret;
}
Then you can safely loop over the input parameters without recomputing the values over and over again:
for(int i=0;i<20;++i)
{
std::cout<<i<<" "<<fibo(i)<<std::endl;
}
Note that this is not only advantageous in printing but also for the calculation itself (at least as long as you call the function more than once).
Beside the above, you should also consider using long or double for the return type, as int will overflow more quickly.
EDIT: Ok, after your edit I don't know whether my answer exactly fits to your question, but I think it's a good advice anyway.
But here is another quick alternative which comes close, I guess:
int fibo(int n, bool first=true)
{
int ret=0;
if(n>2)
{
ret=fibo(n-1,false)+fibo(n-2,false);
}
else
{
ret=1;
}
if(first)
{
std::cout<<ret<<std::endl;
}
return ret;
}
DEMO

Related

Too many recursive calls or too many cout? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Prints specific sequence by given n. For example n=1: 1, n=2: 121, n=3,1213121, n=4: 121312141213121 and so on. But for n > 11 the program stops working after 3556 cout. I think the problem is too many cout or too many recursive calls, but im not sure how to fix it or even is that really the problem. Please let me know if u have any solutions. Thank you so much!
#include <iostream>
using namespace std;
int findNumberByIndex(int index, int& number, int n) {
if (index < 0) {
return 0;
}
if (index % 2 == 0) {
return 1;
}
if (index == ((int)pow(2, number - 1) - 1)) {
return number;
}
index -= (int)pow(2, number);
findNumberByIndex(index, number, n);
}
int printSeq(int rowLen, int& index, int& number, int n, int& counter) {
if (index == rowLen) {
return 0;
}
int result = findNumberByIndex(index, number, n);
if (result == 0) {
number++;
}
else {
cout << result;
index++;
number = 2;
}
printSeq(rowLen, index, number, n, ++counter);
}
int main()
{
int n, index = 0, number = 2, seqLen = 1;
cin >> n;
int counter = 0;
if (n < 0 || n >= 20) {
return 0;
}
int rowLen = ((int)pow(2, n - 1) + (int)pow(2, n - 1) - 1);
printSeq(rowLen, index, number, n, counter);
cout << endl;
return 0;
}
In the definition of findNumberByIndex, you forgot to
return findNumberByIndex(index, number, n);
In the definition of printSeq, you forgot to
return printSeq(rowLen, index, number, n, ++counter);
This leads to undefined behaviour.
Regarding your hypothesis
I think the problem is too many cout or too many recursive calls
Unless specific concerns you can revoke the idea of "too many output". You could suffer from a too deep recursive call tree, but in your specific example your functions are tail-recusrive. With optimization correctly turned on, any decent compiler should optimize them.

Code runs but shows no output after inputting a value [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I'm trying to implement dp on a fibonacci sequence using vector.If i declare memo globally as an array with given size it runs fine.But while using vector it shows no output on the console.
What seems to be the problem here?
#include<bits/stdc++.h>
using namespace std;
int fib(int n)
{
vector<int>memo;
int f;
if(memo[n]!=0)
return memo[n];
if(n<=2)
return 1;
else
f = fib(n-1)+fib(n-2);
memo.push_back(f);
return f;
}
int main()
{
int num;
cin>>num;
cout<<fib(num);
}
The problem here is your declaration of memo:
vector<int>memo;
It is not static, and thus goes out of scope every time the function exits. However, you seem to expect it to still be in scope when the function exits.
Thus, make it static:
static vector<int>memo;
Side note: I would check that n is less than memo.size() before trying to do something like if(memo[n]!=0), because if n is greater than the size, then I believe this is undefined behavior.
Side note 2: You shouldn't include bits/stdC++.h
Here's the corrected code.
#include <iostream>
#include <vector>
using namespace std;
int fib (int n)
{
static vector<int>memo = {1, 1}; // should be static. also init it.
int f;
if (n < memo.size () && memo [n] != 0) // check the size of vector before accessing
return memo [n];
if (n <= 2)
return 1;
else
f = fib (n - 2) + fib (n - 1); // n-2 should be found and inserted before n-1
memo.push_back (f);
return f;
}
int main ()
{
int num;
cin >> num;
cout << fib (num);
}
There were three main issues with the code.
memo should have been declared as static. Previously with each call to fib(), it was creating a fresh 'memo' variable.
memo[n]!=0 might cause a segfault since the vector could be small. You should check the size before referencing nth item.
You were pushing the n'th value to (n-2)'th place. So let's first initialize the vector with {1,1}
Now the series will be generated as...
1 1 2 5 8 13 21 34 55
There are some problems in your code:
You are not allocating space on memo and this is why you get no output.
memo must be static so it lives over the recursion and you can get real memoization
You are using memo.push_back(f);. This defeats memoization because the indices will not correspond to what you want to find in memo
Fixing these issues leads to a code like this:
#include<iostream>
#include<vector>
using namespace std;
int fib(int n)
{
static vector<int> memo(n + 1, 0);
if (n > memo.capacity() - 1)
memo.resize(n + 1, 0);
int f;
if(memo[n]!=0)
return memo[n];
if(n<=2)
return 1;
else
f = fib(n-1)+fib(n-2);
memo[n] = f;
return f;
}
int main()
{
int num;
cin >> num;
cout << fib(num) << endl;
}
The reason nothing is shoring it is the program is running, but you don't know. Change to this it will show.
cout << "Enter a number : ";
cin >> num;
because you are using recursive, in the fib() function, you create memo multiple times. This will return "program terminated with signal 11 segmentation fault"
When you first call fib(), there's nothing in the memo, so you cannot do memo[n].
Hope this helps.
I figured it out.
I changed the checking statement
if(memo[n]!=0)
to this if(!memo.empty()).
And the rest are all the same.
This approach - recursion with memoization - is much easier with a map:
#include <iostream>
#include <map>
using namespace std;
int fib(int n) {
static map<int, int> memo; #pairs are n, f
int f = 0;
if (memo.count(n) > 0)
return memo.at(n);
if (n <= 2 )
return 1;
else
f = fib(n - 1) + fib(n - 2);
memo.emplace(n, f);
// cout << n << " " << f << endl; #run this with and w/o 'static' to see effect
return f;
}
int main() {
for (int i = 1, i < 12, i++)
cout << fib(i) << " ";
cout << endl;
}
gives:
1 1 2 3 5 8 13 21 34 55 89
[Edit] : Here's the vector version, it needed this loop inside however:
int fibVec(int n) {
static vector<int> memo;
int f = 0;
for (int i = 0; i < memo.size(); i++) { //search the vector by index
if (i == n)
return memo[i];
}
if (n <= 2 )
return 1;
else
f = fib(n - 1) + fib(n - 2);
memo.push_back(f);
return f;
}

When i recurse the following code on function prime the program crashes what is wrong in my code?

Whenever I try to recurse in the function prime, my program crashes at that step. I think the problem is passing the function small as a recursion. What am I doing wrong?
#include <iostream>
using namespace std;
int smallest(int n) {
for( int x = 2 ; x <= n/2 ; x++){
if (n%x==0) {
return x;
}
else {
return 0;
}
}
}
int prime(int n, int(*small)(int)) {
int factor;
if (n == 1){
return 0;
}
else {
factor = n % small(n);
cout << small(n) << endl;
return prime(factor , small);
}
}
int main() {
prime(50 , &smallest);
return 0;
}
As the comments point out, when small returns 0, you continue recursing when you shouldn't. This can be solved with a small update to your base case:
if (n <= 1){
return 0 ;
}
Furthermore, it's worth pointing out that as it stands, your prime function will never call itself more than once. When you call smallest, you are guaranteed to get a prime number!

Iteration counter not incrementing [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I wrote a program in c++ to print all the primes up to 100, but it just writes "hello world", and then hangs. Why is that?
#include <iostream>
bool is_prime(int num)
{
if(num == 1)
{
return false;
}
for(int i = 2; i < num; i++)
{
if(num % i == 0)
{
return false;
}
}
return true;
}
int increase(int i)
{
return i++;
}
int main()
{
std::cout << "hello world!!" << std::endl;
int i = 1;
while(i < 100)
{
i = increase(i);
if(is_prime(i))
{
std::cout << i << " is prime" << std::endl;
}
}
}
return i++; this statement would return the original value of i, not the incremented one.
You need return ++i; or return i + 1 (thanks to #interjay for pointing that). The later return i + 1; makes it clear that only the return value matters, and not the new value of i.
The effect of post increment i++ would be visible on the next line (or usage of i).
Not really sure, if you need a separate method for incrementing your variable i, you can do that at in your while loop.
while(i < 100)
{
if(is_prime(i))
{
std::cout << i << " is prime" << std::endl;
}
i++;
}
You can also use a for loop, instead of while since you are working with a range of values.
for(i = 1; i < 100; i++)
{
if(is_prime(i))
{
std::cout << i << " is prime" << std::endl;
}
}
Try this:
int increase(int i)
{
return ++i;
}
to get the incremented value of i else you will get the original value of i which will lead you to infinite loop.
The better approach would be to use(for clarity):
int increase(int i)
{
return i+1;
}
You are calling i++. i++ remembers what value i had and returns that. Try to call ++i.
return i++; returns i then increase i in function stack,
use return ++i; instead.
remember doing something on X++ first do something then increase X.
the problem is that ur increase function keeps returning 1. To fix the issue, change i++ to ++i, the second one modify i by adding 1 before returning
why create a function to increase i. just i = i+1;
The problem is with i++; should be change to ++i;
i++ evaluates i and then increments i, whereas it should be increment i before you evaluate..
Another problem start from 5 instead of 2 since you already handled the case
bool is_prime(int num)
{
if(num == 1)
{
return false;
}
if(num == 2 || num == 3)
{
return true;
}
for(int i = 5; i < num; i++)
{
if(num % i == 0)
{
return false;
}
}
return true;
}
Another way of doing prime numbers:
bool is_prime(int num)
{
while(1)
{
int div = x-1;
if(x%div==0)
return false;
else
if(div != 1)
div--;
else
return false;
}
}
I++ increments I after executing the line. ++I increments I before executing the line.
You may check operator precedence (it works for c++ also)
c operator precedence
Note 2 explains why return I++ does not work.

Recursive/iterative functions

I'm having a bit of a hard time creating a function, using iteration and recursion to find the sum of all even integers between 1 and the number the user inputs. The program guidelines require a function to solve this three ways:
a formula
iteration
recursion
This is what I have so far:
#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;
void formulaEvenSum(int num, int& evenSum)
{
evenSum = num / 2 * (num / 2 + 1);
return;
}
void loopEvenSum(int num, int& evenSum2)
{
}
int main()
{
int num, evenSum, evenSum2;
cout << "Program to compute sum of even integers from 1 to num.";
cout << endl << endl;
cout << "Enter a positive integer (or 0 to exit): ";
cin >> num;
formulaEvenSum(num, evenSum);
loopEvenSum(num, evenSum2);
cout << "Formula result = " << evenSum << endl;
cout << "Iterative result = " << evenSum2 << endl;
system("PAUSE");
return 0;
}
Using iteration to find the sum of even number is as given below.
void loopEvenSum(int num, int &evenSum2)
{
evenSum2=0;
for (i=2;i<=num;i++)
{
if(i%2==0)
evenSum2+=i;
}
}
The following code though not the most efficient can give you an idea how to write a recursive function.
void recursiveEvenSum(int num,int &evenSum3,int counter)
{
if(counter==1)
evenSum3=0;
if(counter>num)
return;
if(counter%2==0)
evenSum3+=counter;
recursiveEvenSum(num,evenSum3,counter+1);
}
Now you can call recursiveEvenSum(...) as
int evenSum3;
recursiveEvenSum(num,evenSum3,1);
You should be able to build an iterative solution using a for loop without too much problem.
A recursive solution might take the form:
f(a)
if(a>0)
return a+f(a-1)
else
return 0
f(user_input)
You have to differentiate between a case where you "dive deeper" and one wherein you provide an answer which doesn't affect the total, but begins the climb out of the recursion (though there are other ways to end it).
An alternative solution is a form:
f(a,sum,total)
if(a<=total)
return f(a+1,sum+a,total)
else
return sum
f(0,0,user_input)
The advantage of this second method is that some languages are able to recognise and optimize for what's known as "tail recursion". You'll see in the first recursive form that it's necessary to store an intermediate result for each level of recursion, but this is not necessary in the second form as all the information needed to return the final answer is passed along each time.
Hope this helps!
I think this does it Don't forget to initialize the value of evenSum1, evenSum2 and evenSum3 to 0 before calling the functions
void loopEvenSum(int num, int& evenSum2)
{
for(int i = num; i > 1; i--)
if(i%2 == 0)
evenSum2+=i;
}
void RecursiveEvenSum(int num, int & evenSum3)
{
if(num == 2)
{
evenSum3 + num;
return;
}
else
{
if(num%2 == 0)
evenSum3+=num;
num--;
RecursiveEvenSum(num, evenSum3);
}
}
void loopEvenSum(int num, int& evenSum2)
{
eventSum2 = 0;
for(int i = 1 ; i <= num; i++){
(i%2 == 0) eventSum += i;
}
}
void recurEvenSum(int num, int& evenSum3)
{
if(num == 1) return;
else if(num % 2 == 0) {
eventSum3 += num;
recurEvenSum(num-1, eventSum3);
}
else recurEvenSum(num-1, eventSum3);
}
btw, you have to initialize evenSum to 0 before calling methods.
the recursive method can be much simpler if you return int instead of void
void iterEvenSum(int num, int& evenSum2)
{
evenSum2 = 0;
if (num < 2) return;
for (int i = 0; i <= num; i+=2)
evenSum2 += i;
}
int recurEvenSum(int num)
{
if (num < 0) return 0;
if (num < 4) return 2;
return num - num%2 + recurEvenSum(num-2);
}
To get the sum of all numbers divisible by two in the set [1,num] by using an iterative approach, you can loop through all numbers in that range, starting from num until you reach 2, and add the number of the current iteration to the total sum, if this is divisible by two.
Please note that you have to assign zero to evenSum2 before starting the loop, otherwise the result will not be the same of formulaEvenSum().
void loopEvenSum(int num, int& evenSum2)
{
assert(num > 0);
evenSum2 = 0;
for (int i=num; i>=2; --i) {
if (0 == (i % 2)) {
evenSum2 += i;
}
}
}
To get the same result by using a recursive approach, instead of passing by reference the variable that will hold the sum, i suggest you to return the sum at each call; otherwise you'll need to hold a counter of the current recursion or, even worse, you'll need to set the sum to zero in the caller before starting the recursion.
int recursiveEventSum(int num)
{
assert(num > 0);
if (num == 1) {
return 0;
} else {
return ((num % 2) ? 0 : num) + recursiveEventSum(num-1);
}
}
Please note that, since you get an even number only if you subtract two (not one) from an even number, you could do optimisation by iterating only on those numbers, plus eventually, the first iteration if num was odd.