My program seems to be crashing every time it recursive calling in the minimum function. Can anyone tell me why it is crashing. It would instantly freeze after i call the minimum function. Is it because im using a vector?
#include <iostream>
#include <vector>
#include <math.h>
#include <algorithm>
using namespace std;
int minimum(vector<int> denom, int s, int N) //take in denomination , sizeofcoin, and value of N
{
if(N == 0)
{
return 1;
}
else if(N < 0 || (N > 0 && s <=0))
{
return 0;
}
else
{
return min(minimum(denom,s - 1, N), 1 + minimum(denom, s,N-denom[s-1]));
}
}
int main()
{
int N;
unsigned int sizeofcoin;
cout << "Enter the value N to produce: " << endl;
cin >> N;
cout << "Enter the number of different denominations: " << endl;
cin >> sizeofcoin;
vector<int> denom(sizeofcoin);
for(unsigned int i= 0; i < sizeofcoin; i++)
{
cout << "Enter denomination #" << (i+1) << endl; //save all the denominations in an array
cin >> denom[i];
}
sort(denom.begin() , denom.end(),greater<int>()); //sort the array from largest to smallest
if(denom.back() != 1) //check the end of the array (since the back is smallest now) if it has 1
{
denom.push_back(1); //Will include 1 if the user does not input a 1 (doesn't have to be used)
}
minimum(denom,sizeofcoin,N);
return 0;
}
I tried to explain your minimum() function to your rubber duck, and your rubber duck has a question for you. Here's how our conversation went:
int minimum(vector<int> denom, int s, int N) //take in denomination , sizeofcoin, and value of N
{
if(N <= 0)
{
return 0;
}
Me: this minimum() recursive function immediately returns if its third parameter, N, is 0, or negative.
Your Rubber Duck: Ok.
return (minimum(denom,s - 1, N)...
(Here, I tried explaining your first recursion call here, to your rubber duck):
Me: So, this makes a recursive call, with the same parameters, except that the 2nd parameter is decremented. The third parameter is N.
Your Rubber Duck: So, if the third parameter's value, N, is unchanged, and the recursive function returns without recursing only when N is 0 or negative, and the initial call to minimum() passes a value greater than 0 for N, then when exactly do you expect this recursion to stop?
I couldn't answer this question myself, maybe you can explain this to your rubber duck, by yourself. When does recursion stop, here?
You have the recursive call minimum(denom,s - 1, N) so N will never be less than or equal to 0, and the recursion will never end.
This would have been very easy to find out if you learned how to use a debugger, and stepped through the code line by line, and stepped into the recursive calls.
Another thing that I want to point out is that you are trying to return the sum of two values:
(minimum(denom,s - 1, N) + minimum(denom, s,N-denom[s-1])
instead what you should do is:
min(minimum(denom,s - 1, N), 1 + minimum(denom, s,N-denom[s-1]))
The idea is that in first call you've not used any coin but in second call you have used one, so adding 1 for the same.
Look for a Dynamic Programming solution for the same.
https://people.cs.clemson.edu/~bcdean/dp_practice/
Related
I am trying to solve at the following exercise from the C++ Primer Plus book.
Define a recursive function that takes an integer argument and returns
the factorial of that argument. Recall that 3 factorial, written 3!,
equals 3 × 2!, and so on, with 0! defined as 1. In general, if n is
greater than zero, n! = n * (n - 1)!. Test your function in a program
that uses a loop to allow the user to enter various values for which
the program reports the factorial.
I wrote the code that goes into main().
#include <iostream>
using namespace std;
int factorial(int n);
int main()
{
int number= 0;
cout<<"Enter a number(0 to quit): ";
while (cin >> number && number! = 0)
{
cout<< "Here is the factorial of the number: "<< factorial (number) << ". \n"
"Enter next number(0 to quit): ";
}
return 0;
}
Now I can't think of a proper recursive function declaration. Can someone help by writing the easiest (for someone new in programming) to grasp function declaration for this exercise?
When designing a recursive algorithm to calculate the factorial of any number, we must first identify the base case, which is the part of the calculation that we can solve without recursion. That is the case where n = 0 then factorial(n) = 1.
This tells how to solve the problem when nis equal to 0, but what do we do when n is greater than 0? That is the recursive case, or the part of the problem that we use recursion to solve. If n > 0, then factorial(n) = n * factorial(n-1). This states that if n is greater than 0, the factorial of n is n times the factorial of n-1.
int factorial(int n)
{
if (n == 0)
return 1; // base case
else
return n * factorial(n-1); // recursive case
}
I would do something along the lines of:
int factorial(int n){
if(n<=0)
return 1;
int num=factorial(n-1);
if(num)
return n*num;
return 0;
}
You can use very short function as follows, but it the same as the answered provided by #superPhreshHackerKid
int factorial(int n){
if (n > 0)
return n * factorial(n-1);
return 1;
}
Hope it helps
I'm trying to build a recursive call for coin change in c++ . i tried most of the algorithm on the internet but it doesn't seem to apply with vector or it doesn't out the sums of the coin used. Can anyone help me understand what the recursive function has to call? So my algorithm doesn't give me the minimum number of coin used and i don't know how to save the coin used.
int coin(vector<int> denom, int s,int N)
{
if(N == 0)
{
return 1;
}
if(N < 0 || (N > 0 && s < 0))
{
return 0;
}
return min(coin(denom,s - 1, N), 1 + coin(denom, s,N-denom[s-1]));
}
Input a value N:
Input: 40
Input how many denominations:
Input: 3
Denominations #1:
Input: 5
Denominations #2:
Input: 20
Denominations #3:
Input: 30
Output:
Minimum # of coins: 2
Coin used: 20 + 20
Don't want: 30 + 5 + 5
Some points to consider:
Firstly, there is no need to send the number of denominations i.e. s
as an argument to the coin method as long as a vector is being used, because vector has inbuilt size() method which does that job for us.
Secondly, to save the solution you need another vector of int named solution, but this vector is just to keep a record and has nothing to do with the actual recursive implementation and hence, it is defined as a global variable. Alternatively, you could pass it as an argument by reference to the coin method too.
Thirdly, the denominations entered by the user should be sorted before passing them to the coin method. For this, I have used the sort method from the algorithm library.
What the recursive algorithm basically does is:
At each step, it considers the largest denomination d (last element in the sorted denomination vector denom like denom[denom.size() - 1]) which is then removed from the vector using pop_back method of vector.
Using d we find count_d, which is the number of coins of denomination d, used in the solution. We get this by simply applying a div operation like N/d, which gives the Quotient.
Then d is added to the vector solution, count_d number of times.
The recursive call, adds count_d from this iteration and recalls coin with the reduced denominations vector denom and Remainder of the amount N using N%d.
See Quotient and Remainder for clarity of what div / and mod % operators do.
Here is the code:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> solution;
int coin(vector<int> denom, int N)
{
if(N <= 0 || denom.size() <= 0)
{
return 0;
}
int d = denom[denom.size() - 1];
denom.pop_back();
int count_d = N/d;
solution.insert(solution.end(), count_d, d);
return count_d + coin(denom, N%d);
}
int main()
{
int N,s;
cout<<"Input a value N:\nInput: ";
cin>>N;
cout<<"Input how many denominations:\nInput: ";
cin>>s;
vector<int> denom;
for(int i = 0; i < s; i++)
{
int d;
cout<<"Denominations #"<<i+1<<":\nInput: ";
cin>>d;
denom.push_back(d);
}
std::sort(denom.begin(), denom.end());
int minNoOfCoins = coin(denom, N);
cout<<"\nOutput:\nMinimum # of coins: "<<minNoOfCoins;
if(minNoOfCoins > 0)
{
cout<<"\nCoins used: ";
for(int i = 0; i < solution.size(); i++)
{
if(i > 0)
{
cout<<" + ";
}
cout<<solution[i];
}
}
cout<<endl;
system("pause");
}
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).
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;
}
Example: Let’s say your user input is 6.
Then the number of sequences that sum up to 6 is 11 (including 6 itself). This is shown clearly below:
6
5+1
4+1+1
3+1+1+1
2+1+1+1+1
1+1+1+1+1+1
2+2+1+1
3+2+1
4+2
2+2+2
3+3
You SHOULD NOT have any sequences that repeat. You cannot have 2+2+1+1 and 1+1+2+2 as two different combinations!!
CODE:
#include <iostream>
using namespace std;
int sum(double number, int min, int & counter)
{
int temp=0, n;
n=number+temp;
if ((number>=(n/2)) & (number!=0))
{
number --;
temp ++;
while (number>=(n/2))
{
cout << number << "+"<< temp << "\n";
number --;
temp ++;
counter ++;
}
}
else if (number==0)
{
return 0;
}
sum(n-min, 1,counter);
return 0;
}
int main()
{
int number, counter=1;
cout << "Please enter the number: ";
cin >> number ;
cout << "\n";
sum(number, 1, counter);
cout << counter;
return 0;
}
My output is
6
5+1
4+1+1
3+1+1+1
2+1+1+1+1
1+1+1+1+1+1
2+2+1+1
3+2+1
3+1+2
2+3+1
4+2
2+2+2
3+3
0+1
Total out is 13.
Real output which is a shorter version for those of you who dont like whats posted above.
5+1
4+2
3+3
4+1
3+2
2+3
3+1
2+2
2+1
1+2
1+1
0+1
13
Where 1+2 and 2+3 are doubles as listed above.
Any ideas what is wrong here?
I guess it would be easier if you'd sum so that the first summand is always highest possible and you don't allow that of two adjacent summands the second one is greater than the first one.
Just a thought...
I've already posted a solution to it in your previous question:
void sum_r(int n, int m, int cnt, int* nums){
for (;n >= m; m++)
sum_r(n-m, nums[cnt] = m, cnt+1, nums);
if (!n) for (int i=0; i<cnt; i++) printf("%d%c",nums[i],(i==cnt-1)?'\n':'+');
};
void sum(int n){
int nums[100];
return sum_r(n, 1, 0, nums);
};
int main(){
sum(6);
return 0;
};
EDIT: I'll try to explain it better. The main idea is to impose an order on the generated sequence, it will help in avoiding repetition.
We will use the min parameter for that, it will be the smallest possible term we can use from now on in the sequence.
The function sum_r just prints the sequence of values of min at each recursion level.
The num term is used as a kind of accumulator, or the value left "to spare".
We can write a simplier function, that just counts the number of such sequences:
int sum_c(int n, int m){
if (!n) return 1; // termination condition. end of sequence reached with "perfect match". this means we have found 1 additional sequence. Note that it's the only way of adding new values to result.
int comb_cnt = 0;
while (n >= m) { // we need a stop condition, and there is no point in having negative value of (n - m)
comb_cnt += // here we accumulate all the solutions from next levels
sum_c(n-m, m); // how many sequences are for current value of min?
m++; // trying a larger `min`
};
return comb_cnt; // number of sequence fond at this level
};
Here's a hint: The problem is to compute the partitions of the input number. See also: partition function
Well the logical AND operator in C++ is &&, not & as you have in this line:
if ((number>=(n/2)) & (number!=0))