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;
}
Related
Please tell me what is wrong, the output is wrong, shows 4 to me
F1 = 2, Fn = (Fn-1)
2 , n ≥ 2
i. What is the complexity of the algorithm that computes Fn
using the recursive
definition given above.
#include <iostream>
using namespace std;
double calcFn(double,int);
int main()
{
cout << calcFn(2, 4);
cout << endl;
cin.get();
return 0;
}
double calcFn(double F1, int N)
{
cout << endl;
double Fn = F1 * F1;
while (N > 0)
{
N--;
calcFn(Fn, N);
}
return Fn;
}
// CODE DOESNT SHOW the RIGHT oUTPUT
First of all, You have recurrency, so you should not use the loop. Secondly, You do not assign return value. The corrected snippet:
if (N > 0)
{
N--;
Fn = calcFn(Fn, N);
}
Still, I'm not sure about the result, but You can further correct it.
I'm trying to solve the following problem:
What is the smallest number of factoriais summed that are needed to be equal an given number a? (1 ≤ a ≤ 10^5)
Example:
Input: 10, Output: 3. (10 = 3! + 2! + 2!)
Input: 25, Output: 2. (25 = 4! + 1!)
My code:
#include<bits/stdc++.h>
using namespace std;
int a;
int rec(int vet){
int count = 0;
a = a - vet;
if(a >= vet){
count++;
rec(vet);
}
count++;
return count;
}
int main(){
int vet[8] = {1}, count = 0;
cin >> a;
for(int i = 2; i <= 8; i++){
vet[i-1] = vet[i-2]*i;
}
for(int i = 7; i >= 0; i--){
if(a < vet[i]){
continue;
}
count += rec(vet[i]);
}
cout << count << endl;
}
My logic:
1°: a max is equal to 100000, so the maximum fatorial we have to
compare is 8!;
2°: I take a factioral that is equal or nearest small to a,
subtract the factorial from it and count++; If after the subtraction,
a still bigger then my factorial, I do the same step recursively.
This code pass on the base cases, but I got a wrong answer. I wasn't capable to find what case it didn't pass, so I'm here.
Can you find where am I wrong? Or if my solution is not good and I should try another approach.
Thanks for the help!
The problem is easily solved by a recursive approach.
Here is checked code:
#include <iostream>
using namespace std;
int factorial(int n) {
return n<=1 ? 1 : n * factorial(n-1);
}
int MinFact(int number)
{
static int num_of_facts;
int a = 1;
if (number)
{
while(factorial(a+1)<=number)a++;
cout << a << "!" << endl;
num_of_facts++;
MinFact((number-factorial(a)));
}
return num_of_facts;
}
int main()
{
int num;
cout << "Enter number" << endl;
cin >> num;
num = MinFact(num);
cout << "Number of factorials: " << num;
return 0;
}
As I mentioned in the comment, the issue is with the rec function. Due to rec being local, the count is not being incremented correctly.
A simple solution would be to replace the rec function as follows
int rec(int vec) {
int count = a / vec;
a = a % vec;
return count;
}
Edit : for a failing case try 18. The solution will be 3 but you will get 2.
I guess you can figure out how this logic works. If not you could do it with a loop.
I created a prime number checking program which checks the user entered number prime or not.
It detects non prime numbers easily, but when we type prime numbers, it crashes!
I think I know why, but don't know how to rectify them...
Here's my Program:
#include "stdafx.h"
#include <iostream>
#include<iomanip>
#include <cmath>
using namespace std;
float Asker()
{
float n;
cin >> n;
return n;
}
int Remainder(int n, int x)
{
int q = n%x;
if (q == 0)
return 1;
else
Remainder(n, x + 1 > n);
/*
Here is the PROBLEM
*/
return 0;
}
int main()
{
cout << "Enter your Number : ";
float n = Asker();
int r = Remainder(n, 2);
if (r == 1)
cout << "That Ain't Prime!\n";
else
cout << "Yep Thats Prime!\n";
main();
return 0;
}
Suppose, when I enter 7, I know that, it checks upto 6, then it should crash!(due to x + 1 > n condition). I don't know how to return 0 when it fails the else condition...
To answer to your question "Whats wrong with my Prime number Checker?" a lot of things are wrong:
Don't call main() in main. That's not how you do recursion
int Remainder(int n, int x) and you call it with a float (cast is missing) then with a bool : Remainder(n, x + 1 > n);
Your asker doesn't need to be a float
About the recursion within main there is two reason:
With this config you'll get an endless loop;
ISO C++ forbids taking address of function '::main'
//#include "stdafx.h" //This is an invalid header.
#include <iostream>
#include<iomanip>
#include <cmath>
using namespace std;
float Asker()
{
float n;
cin >> n;
return n;
}
int Remainder(int n, int x)
{
int q = n%x;
if (q == 0 && n>2 )//'2' have to be excluded.
//otherwise 2%2==0 can set
//'2' as a non prime which is wrong
return 1;
else if(x+1<n)
Remainder(n, x + 1);
/*
Here was the PROBLEM
Remainder(n, x + 1 > n) 'x + 1 > n ' is an invalid paramrter.
*/
else
return 0;
}
int main()
{
cout << "Enter your Number : ";
float n=Asker();
int r=1; //It is essential to initialize r to 1
if(n!=1) //Have to exclude '1'. Otherwise
//It will assign '1' as prime which is wrong
r = Remainder(n, 2);
if (r == 1 )
cout << "That Ain't Prime!\n";
else
cout << "Yep Thats Prime!\n";
//main(); //Why are you calling main again?
return 0;
}
Your first error was " #include "stdafx.h" ". Where'd you get this header?
Then inside int Remainder(int n, int x) function you used recursion and sent an invalid syntax " Remainder(n, x + 1 > n) ". You can't use syntax like x+1>n in a parameter.
After that why are you calling main() inside main function?
And your algorithm needed some touch which I have added and explained in comment.
But you should know that the shortest way to check a prime number is to check n%x==0 till x<=square_root(n).
First of all you don't have to check modulo for all numbers up to n-1: it is sufficient to check modulo up to sqrt(n). Second, you should return 0 from the function if the next divisor to check is larger than sqrt(n). Here is the corrected Remainder function.
int Remainder(int n, int x)
{
int q = n%x;
if (q == 0)
return 1;
else
{
if(x+1 > std::sqrt(n)) return 0;
else return Remainder(n, x + 1);
}
}
Finally, it is better to change the type of n in main and Asker from float to int, and return type of Asker should be int too.
This is not an exhausting list of what's wrong with the prime number checker in focus - just a way to fix it quickly. Essentially, such prime number checker shouldn't use recursion - it's more neat to just iterate over all potential divisors from 2 to sqrt(n).
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
I was writing a small snippet to get a Fibonacci number sequence depending on the user input. If the user supplies 4 as an input, it should return him the first N members of the Fibonacci sequence.
#include <iostream>
using namespace std;
int main (){
int a = 0;
int b = 1;
int c;
int n = 3;
n -= 2;
if (n == 1){
cout << a << endl;
} else {
cout << a << b << endl;
for (int i=0;i<n;i++){
c = b + a;
cout << c << endl;
a = b;
b = c;
}
}
}
However, I end up getting a 0 as an output for whatever number I supply. I have this working in PHP and I kinda miss where I've blundered. I guess I don't actually render input and output properly.
int a =0;
int n = 3;
n -= 2;
if (n == 1){
cout << a << endl;
}
You have n equal to 3, you subtract 2, thus n equal to 1, so, you enter the if body and output a, which is zero.
[EDIT]
You don't seem to get any input -as stated in a comment- in your program (you could use std::cin or std::getline() for this), but you probably mean that you have the input hard-coded, by changing the value of n by hand.
You may want to check how the Fibonacci series program is expected to work:
Fib. at Rosseta page.
Fib. with recursion
Non-recursive Fib.
After reading the links I provided above, you should be able to see that your code should be changed to this:
#include <iostream>
using namespace std;
int main (){
int a = 1;
int b = 0;
int c;
int n = 10; // "input" is 10
if (n == 0 || n == 1) { // 0 and 1 case
cout << n << endl;
} else {
for (int i = 2; i <= n; ++i) { // here you want to reach n
c = a + b;
b = a;
a = c;
}
cout << c << endl;
}
return 0;
}
However, the code above outputs only the result. You should slightly modify it to get the terms of the sequence, but I'll leave you have some fun too.
In order to really let the user input the number, change:
int n = 10;
to
int n;
std::cout << "Please, input.\n";
std::cin >> n;
However, letting user inputting must be followed by validation of the input. You see users can, by accident or not, provide input in your program, that can cause undefined behaviour.
The sequence you want is 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, ...
As I pointed out in a comment to another answer, your code does not produce a correct Fibonacci sequence. F(3) isn't the problem with your code; the problem is that you get confused between all the variables, a, b, c and use them to mean different things at once.
You also incorrectly decrement n: your code does it in the wrong place, and even if you move it to the right place, it wouldn't help as the operation would make n go negative.
Your existing Code
Let's walk through your code a bit:
int a = 0;
int b = 1;
int c;
int n = 3;
n -= 2;
Well, this is weird. We set n to 3 then immediately subtract 2, making it 1. This means that if you try to set n to 0, 1, or 2 you end up with n being a negative number. If you set it to 3, you end up with n being 1.
if (n == 1){
cout << a << endl;
}
We're in trouble right here. Remember that you subtract 2 from n which means that for n==3 you will return whatever is in a which is wrong. But even if you meant this to special-case F(1) that code is still wrong because F(1)=1.
else {
cout << a << b << endl;
for (int i=0;i<n;i++){
Remember, that we can get here with n zero or negative. Obviously in the case of n <= 0 this loop will never execute, so c will never be printed.
c = b + a;
cout << c << endl;
Here, we seem to calculate and output the next Fibonacci number by adding the two previous numbers. This should be fine.
a = b;
b = c;
And here, we keep the new Fibonacci number and its predecessor for the next loop iteration, if any.
The problems with this code are, of course, fixable. But the problem is that the existing code is confusing. It outputs all sorts of different values, and it's unclear what variable is supposed to represent.
Looking at this problem, your first instinct would be to make a function which accepts as input a number n and returns F(n) - you could call it fib or somesuch.
Reworking this
So, how to go about writing such a function? Here's a simple recursive implementation that you can use:
int fib(int n)
{
if ((n == 0) || (n == 1))
return n;
return fib(n-1) + fib(n-2);
}
Notice how this function is short, sweet and to the point. There's no need for a ton of variables, no need for complicated control structures or storing state. It almost reads like a text-based description of the Fibonacci algorithm.
Of course, it's not super-efficient and ends up redoing a lot of work. That's a legitimate criticism, but it's unlikely that there performance considerations here.
Still, perhaps you just don't like recursion. Many people think of recursion as a dirty word, and avoid it with a passion. So how about a non-recursive implementation instead? It's possible, but it's a bit more difficult to understand.
int fib (int n)
{
/* F(0) = 0 */
if (n == 0)
return 0;
int a = 0;
int b = 1;
for (int i = 2; i < n; i++)
{
int c = a + b;
a = b;
b = c;
}
/* F(n) = F(n-2) + F(n-1) */
return a + b;
}
This is a little bit more efficient and not that much more difficult to understand.
I hope that this helped.
Try this which would give you the list you needed.
#include <iostream>
using namespace std;
int fib(int num){
int ans;
if (num >2) {
ans = fib(num-1) + fib(num-2);
}
else
ans = 1;
return ans;
}
int main()
{
int num, x=1;
cin >> num;
while (num >= x) {
cout << fib(x) <<" ";
x++;
}
return 0;
}