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
Related
I could use some help with my programming assignment. I need to use a recursion in order to make arithmetic_series = arithmetic_series_recursive. Right now my recursive function is not working properly. It only works up until the number three. The functions are supposed to take the input from the user and form a number based on the number of integers inside the number. IE if the user entered 3 it would be 1*2*3 = 6.
int arithmetic_series(int n){
int total = ((n+1) * n )/ 2;
cout << total << endl;
return total;
}
int arithmetic_series_recursive(int n){
if(n==1){
return 1;
}else{
return n*arithmetic_series_recursive(n-1);
}
}
Your first function finds the sum of integers from 1 to n. Your second function finds the product of the that range, or !n. I don't know of any simplification you could use in your first function.
If you meant to find the sum of the numbers, you can change the your second function to preform an addition :
int arithmetic_series_recursive(int n) {
if (n == 1) {
return 1;
}
else {
return n + arithmetic_series_recursive(n - 1);
}
}
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");
}
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/
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 wrote this function that supposed to find smallest positive integer that is divisible by every number 1 through 20. I get "stack overflow error", even though, when I test for numbers 1 through 10, it works just fine.
here is my code:
#include<iostream>
#include<cstdlib>
using namespace std;
// function prototype
int smallPos(int k, int m,int n);
int main(){
printf("the smallest positive number that is divisible by 1 through 20 is %d ", smallPos(1,1,13));
}
int smallPos(int k, int n, int m){
int div=0;
for(int i = n;i<=m;i++) {
if (k%i==0)
div++;
}
if (div==m) {
return k;
} else {
k+=1;
smallPos(k,n,m);
}
}
Why does it happen? The number shouldn't be that big anyway.
Thank you!
The final condition (div == m) will never be true. For div to become equal to m, the number k should be divisible by all of the numbers in range [n,m).
Edit: I've reread the text in the printf() call to understand what the function does. You're looking for the first number divisible by all numbers in the range. If my calculations are correct, this number should be the product of all unique prime factors of the numbers in the range. For the range [1,13] (as per the function call, not the text), this number should be:
30030 = 1 * 2 * 3 * 5 * 7 * 9 * 11 * 13
Now, this means you are going to invoke the function recursively over 30,000 times, which is obviously way too many times for the size of stack you're using (defaults are relatively small). For a range this size, you should really consider writing an iterative function instead.
Edit: here's an iterative version that seems to work.
int smallPos ( int n, int m )
{
int k = 0;
while ( ++k )
{
int count = 0;
for (int i = n; i<=m; i++)
{
if (k%i==0) {
++count;
}
}
if (count == (m-n+1)) {
return k;
}
}
return k;
}
Indeed, the result for smallPos(1,10), the result is 2520. It seems my previous estimate was a lower bound, not a fixed result.
Your smallPos function incurs undefined behaviour since it is not returning a value in all execution paths. You may want to say return smallPos(k,n,m); in the last part (or just return smallPos(k + 1, n, m); in one go).