Using C++ to figure out the factorial is straightforward enough. To print the values coming up (if factorial is 5) ... 1 * 2, * 3, * 4 * 5 also no problem - as I think I've done below.
But what I'm having a hard time doing is saying show me 5 * 4 then value * 3 then value * 2 etc. I want to be able to print the data going down and I can't seem to figure it out.
#include <iostream>
using namespace std;
int factorial(int n);
int main()
{
int number;
cout << "Enter an integer value ";
cin >> number;
cout << "The factorial of " << number << " is ";
cout << factorial(number) << endl;
}
int factorial(int n)
{
if (n == 0)
return 1; // Base case
else
{
n = n * factorial(n - 1); // Recursive case
cout << " going up" << n << " ";
return n;
}
}
There are a couple of other posts but I didn't find one asking the same thing.
The desired results are: 20 60 120
The current results are 1 2 6 24 120
Please advise.
Thank you.
Just change where you are printing the value
else
{
n = n * factorial(n - 1); // Recursive case
cout << " going up" << n << " ";
return n;
}
to
else
{
cout << " going down" << n << " ";
n = n * factorial(n - 1); // Recursive case
return n;
}
The above would print 5 4 3 2 1 but if you want something like
5 20 60 ...
Than you have to change the recursive definition a bit.
#include<iostream>
using namespace std;
int factorial(int n,int temp);
int main()
{
int number;
cout << "Enter an integer value ";
cin >> number;
cout << "The factorial of " << number << " is ";
cout << factorial(number,1) << endl;
}
int factorial(int n,int temp)
{
if (n == 0)
return temp; // Base case
else
{
cout << " going down" << n * temp << " ";
factorial(n - 1,n*temp); // Recursive case
//return n;
}
}
Related
Q) Write a program that defines and tests a factorial function. The factorial of a number is the product of all whole numbers from 1 to N.
For example, the factorial of 5 is 1 * 2 * 3 * 4 * 5 = 120
Problem: I am able to print the result,but not able to print like this :
let n = 5
Output : 1 * 2 * 3 * 4 * 5 = 120;
My Code:
# include <bits/stdc++.h>
using namespace std;
int Factorial (int N)
{
int i = 0;int fact = 1;
while (i < N && N > 0) // Time Complexity O(N)
{
fact *= ++i;
}
return fact;
}
int main()
{
int n;cin >> n;
cout << Factorial(n) << endl;
return 0;
}
I am able to print the result,but not able to print like this : let n
= 5 Output : 1 * 2 * 3 * 4 * 5 = 120;
That's indeed what your code is doing. You only print the result.
If you want to print every integer from 1 to N before you print the result you need more cout calls or another way to manipulate the output.
This should only be an idea this is far away from being a good example but it should do the job.
int main()
{
int n;cin >> n;
std::cout << "Factorial of " << n << "!\n";
for (int i =1; i<=n; i++)
{
if(i != n)
std::cout << i << " * ";
else
std::cout << n << " = ";
}
cout << Factorial(n) << endl;
return 0;
}
Better approach using std::string and std::stringstream
#include <string>
#include <sstream>
using namespace std;
int main()
{
int n;
cin >> n;
stringstream sStr;
sStr << "Factorial of " << n << " = ";
for (int i = 1; i <= n; i++)
{
if (i != n)
sStr << i << " * ";
else
sStr << i << " = ";
}
sStr << Factorial(n) << endl;
cout << sStr.str();
return 0;
}
i have this program assignment and one part of it is trying to find the max power a number will go to(x) without exceeding a number the user inputs it not to exceed(y). we are using it in a function. this is the whole program and what i have for max power it just keeps returning 0. it is the int maxpower(int x, int y) function i am trying to figure out
#include <iostream>
#include <cmath>
using namespace std;
// meunue where you can get your options from
void menue() {
cout << "choose the following options:" << endl;
cout << "1) Power of x raised by y." << endl;
cout << "2) Find the max power a number can be raised to." << endl;
cout << "3) Print out a number with its digits in reversed order." << endl;
cout << "4) Sum of integers from 1 to n." << endl;
cout << "5) Product of integers from 1 to n." << endl;
cout << "6) Quit" << endl;
}
//functions for finding the power usign recursion
int Power(int a, int b) {
int x = 1, i;
for (i = 1; i <= b; i++) {
if (b == 0) {
return Power(a, b--);
}
else {
x = x * a;
}
}
return x;
}
int maxpower(int n, int max_value) {
int temp = temp * n;
if (temp > max_value)
return 0;
else return maxpower(n, max_value + 1);
}
int reverse(int number) {
int lastDigit, numberOfDigits, sign = 1;//sets the sign equal to one
// if number is less than 0 returns 0
if (number < 0) {
return 0;
}
else
//if a number is under 10 than it can not be switched so you times the number by 10 and switch it.
if (number < 10)
return number * sign;
lastDigit = number % 10;
number = number / 10;
numberOfDigits = log10(number) + 1;
//recursive statement that calls the function
return (lastDigit * pow(10, numberOfDigits) + reverse(number)) * sign;
}
//finding the sum
int sum(int n) {
if (n != 0) {
return n + sum(n - 1);//recursive statement
}
else {
return n;
}
}
//finding the product
int product(int n) {
int temp;
if (n <= 1) {
return 1;
}
else {
temp = n * product(n - 1);
// recursive statement setting temp == to recursive statement
return temp;//returning temp
}
}
int main() {
int a;
int x;
int y;
int length = 0;
int temp;
int results;
// calls menue and get prints all the options
do {
menue();
//inserts the choice
cin >> a;
cout << "you choose:" << a << endl;//prints the choice out.
//switch statement that will take account for the number you choose and prints the results
switch (a) {
case 1:
cout << "enter the number to raise" << endl;
cin >> x;
cout << " enter the power to raise to: " << endl;
cin >> y;
Power(x, y);
cout << "the result is:" << Power(x, y) << endl;
break;
case 2:
cout << "Enter the number to raise:" << endl;
cin >> x;
cout << "Enter the number not to exceed:" << endl;
cin >> y;
maxpower(x, y);
cout << "the result is:" << maxpower(x, y) << endl;
break;
case 3:
cout << " enter numbers to be reversed by: " << endl;
cin >> x;
temp = x;
while (temp != 0) {
length++;
temp = temp / 10;
}
reverse(x);
cout << "the result is:" << reverse(x) << endl;
break;
case 4:
cout << "enter the number to sum to: " << endl;
cin >> x;
sum(x);
cout << "the result is:" << sum(x) << endl;
break;
case 5:
cout << "enter the number to multiply to:" << endl;
cin >> y;
product(y);
cout << "the result is:" << product(y) << endl;
break;
case 6:
cout << "good bye!!" << endl;
break;
}
} while (a != 6);
return 0;
}
I don't think it's necessary to use recursion for this problem. Moreover, recursion is creating a lot of overhead while solving it with a loop works just fine. Do you have to use recursion? If so, then disregard this answer :p. But you'll find below a solution that will work.
Note the #include <math.h> bit - you need that to use pow(base, exponent).
Also, while(true) is definitely not the best practice, but as long as you have sufficient checks to get out of the loop properly then you're ok. Hence the max_iteration and the actual return statement that you're looking for.
Best of luck!
#include <iostream>
#include <math.h>
int maxpower(int n, int max_value) {
if ( n > max_value ) return 0;
int previous, current = 1;
int max_iteration = 0;
while (true) {
if (max_iteration >= 1000) return -1;
if (pow(n, current) > max_value) {
return previous;
}
previous = current;
current++;
max_iteration++;
}
}
int main() {
int x;
int y;
int result;
std::cout << "Enter the base: ";
std::cin >> x;
std::cout << "Enter the max number x^pow should not exceed: ";
std::cin >> y;
result = maxpower(x, y);
if (result == -1) {
std::cout << "Max iteration reached." << std::endl;
}
else {
std::cout << result << " is the maximum power such that " << x << "^" << result << " does not exceed " << y << std::endl;
}
return 0;
}
As an example of output:
If x = 2 and y = 32, the program will return 5 as the max power (i.e. 2^5 = 32 and is not greater than, but 2^6 > 32).
EDIT:
I realized after I posted that all of your functions are recursive, so perhaps that's a requirement for your assignment. Anyway, below is a recursive solution:
int maxpower_rec_helper(int n, int power, int max_value) {
if (pow(n, power) > max_value) return power - 1;
return maxpower_rec_helper(n, power + 1, max_value);
}
int maxpower_rec(int n, int max_value) {
if ( n > max_value ) return 0;
return maxpower_rec_helper(n, 1, max_value);
}
You'll need a helper function to give the initial power 1, and so as not to disturb your max_value.
return power - 1; is essentially the same thing as return previous; in the iterative example above.
I'm writing a code that requires pentagonal numbers to be limited to ten per line, however I can't get it to work. My code is:
#include <iostream>
using namespace std;
int getPentagonalNumber(int n)
{
/*equation to calculate pentagonal numbers*/
return (n * (3 * n - 1) / 2);
}
int main()
{
/*Ask the user to put in the number of results*/
int userInput;
cout << "How many pentagonal numbers would you like to be displayed: ";
cin >> userInput;
cout << endl;
cout << "results are: " << endl;
/*Loop to generate the numbers for the equation*/
for (int n = 1; n <= userInput; n++)
{
cout << getPentagonalNumber(n) << " ";
}
return 0;
}
Does this do what you want:
#include <iostream>
using namespace std;
int getPentagonalNumber(int n)
{
/*equation to calculate pentagonal numbers*/
return (n * (3 * n - 1) / 2);
}
int main()
{
/*Ask the user to put in the number of results*/
int userInput;
cout << "How many pentagonal numbers would you like to be displayed: ";
cin >> userInput;
cout << endl;
cout << "results are: " << endl;
/*Loop to generate the numbers for the equation*/
for (int n = 1; n <= userInput; n++)
{
cout << getPentagonalNumber(n) << " ";
if (n % 10 == 0)
cout << endl;
}
return 0;
}
?
I added a new line output every time n is divisible by 10.
For my c++ data structures class our assignment is to print a pattern of stars like this
*
* *
* * *
* * * *
* * * *
* * *
* *
*
with the number of lines in the pattern determined by the user input. So the pattern above would print if the user enters a 4.
We had a previous assignment where we had to print the opposite pattern, one like this
* * * * *
* * * *
* * *
* *
*
*
* *
* * *
* * * *
* * * * *
and the above pattern would print if the user enters a 5. This pattern, the one above, I had no problem with. I used a for loop to print the top half, then recursively called the function again, and then the same for loop to print the bottom half in the opposite direction. For reference, here's the code I used for the above pattern:
int main()
{
int number;
cout << "Enter the number of lines in the grid: ";
cin >> number;
printStars(number);
cout << endl << "Grid Pattern Complete - End of Program.";
return 0;
} // end of main
void printStars(int num)
{
if (num < 0) cout << endl << "Please enter a non negative number." << endl;
else{
if (num == 0) return;
else{
for (int q = 1; q <= num; q++)
{cout << "*";}
cout << endl;
printStars(num - 1);
for (int q = 1; q <= num; q++)
{cout << "*";}
cout << endl;
}
}
} // end printStars
This function works like how I want it, so I figured I would use it as a reference to complete the second assignment. The problem I'm having is that, while it was easy enough to complete the first assignment (printing a line of 4 stars, then a line of 3, then a line of 2 , then a line of 1, then all that again in reverse order), I can't seem to figure out how to format the for loops to print the pattern starting with a line of 1 star, then a line of 2, then a line of 3, and so on, until its called recursively and printed again in reverse order.
For reference, this is the code I have (so far) for the second assignment:
int main()
{
int number;
cout << "Enter the number of lines in the grid: ";
cin >> number;
printStars(number, 0);
cout << endl << "Grid Pattern Complete - End of Program.";
return 0;
}
void printStars(int num, int num2)
{
if (num2 <= num)
{
for (int e = num; e > num2; e--)
{
cout << "*";
}
cout << endl;
printStars(num - 1, num2);
}
}
The only thing this prints is the second half of the pattern;
(If the user enters a 5)
* * * * *
* * * *
* * *
* *
*
And even to make this work, I have to recursively call the function at the end, which is out of order.
I guess I'm just confused on how this recursion is supposed to work but I've been playing with it for hours and I can't seem to reformat it or rearrange it or restructure it so that it prints like I need it to. Can someone give me some guidance? Just maybe write some pseudo code to help me out. This is for school so I need to be able to understand it but I'm really lost right now.
Try this. It is minimally modified version of your code. The upper limit is passed to all recursions and the recursive function calls are performed with the values starting with 1 (only 1 start in the first line):
void printStars(int num, int limit)
{
if (num >limit) return;
else{
for (int q = 1; q <= num; q++)
{cout << "*";}
cout << endl;
printStars(num +1, limit);
for (int q = 1; q <= num; q++)
{cout << "*";}
cout << endl;
}
}
int main()
{
int number=5;
cin>>number;
printStars(1, number);
return 0;
} // end of main
I tested it and the result is correct. The link is:
http://ideone.com/ez6pZ5
ideone result:
Success time: 0 memory: 3144 signal:0
*
**
***
****
*****
*****
****
***
**
*
For the sake of the exercise - how about a recursive function to print the stars and another to determine the number of stars:
string ReturnStars(int number)
{
if (number > 1)
return "*" + ReturnStars(number -1);
return "*";
}
void PrintStars(int start, int lines)
{
cout << ReturnStars(start) << endl;
if (start < lines)
PrintStars(start + 1, lines);
cout << ReturnStars(start) << endl;
}
int main()
{
int numberLines = 1;
cout << "Please enter a positive number to print a star pattern for: ";
cin >> numberLines;
PrintStars(1, numberLines);
return 0;
}
Example of output:
I suggest using two recursive functions, one to print in increasing order and the other to print in decreasing order.
After you get the two functions working, save a copy of the program.
You can then try to create one function the performs both increasing and decreasing orders of stars.
You aren't printing out the stars after your recursion call:
void printStars(int num, int num2)
{
if (num2 < num)
{
for (int e = num; e > num2; e--)
{
cout << "*";
}
cout << endl;
printStars(num - 1, num2);
for (int e = num; e > num2; e--)
{
cout << "*";
}
cout << endl;
}
}
note the if condition had to change slightly too. I also agree with Thomas, it might make more sense to structure your recursion differently:
void printStars(int num)
{
for (int i = 1; i <= num; i++)
{
cout << "*";
}
cout << endl;
}
void printStarsRecursive(int stars)
{
if (stars == 0)
return;
printStars(stars);
printStarsRecursive(stars-1);
printStars(stars);
}
int main()
{
int number;
cout << "Enter the number of lines in the grid: ";
cin >> number;
printStarsRecursive(number);
cout << endl << "Grid Pattern Complete - End of Program.";
return 0;
}
If you want to do it recursively, you have to keep in mind that there are multiple states: the state where you're counting up to N, and the state where you're counting back to 1. So if you have to go it recursively, you need to keep track of those extra things:
void printStarsImpl(int count, int initial, int sign)
↑ ↑ ↑
current termination next step
And this function just has to know which next printStarsImpl() function to call - whether we just call with count + sign, whether we flip sign to -1, or whether we do nothing... all after printing count *'s of course.
The initial call is then:
void printStars(int n) {
printStarsImpl(1, n, +1);
}
The straightforward approach if to use the function declared as having only one parameter is the following with using a static local variable in the function
#include <iostream>
void print_stars( size_t n )
{
static size_t m;
if ( m++ != n )
{
for ( size_t i = 0; i < m; i++ ) std::cout << '*';
std::cout << std::endl;
print_stars( n );
}
--m;
for ( size_t i = 0; i < m; i++ ) std::cout << '*';
std::cout << std::endl;
}
int main()
{
while ( true )
{
std::cout << "Enter a non-negative number (0-exit): ";
size_t n = 0;
std::cin >> n;
if ( !n ) break;
std::cout << std::endl;
print_stars( n );
std::cout << std::endl;
}
return 0;
}
The program output can look like
Enter a non-negative number (0-exit): 4
*
**
***
****
****
***
**
*
Enter a non-negative number (0-exit): 3
*
**
***
***
**
*
Enter a non-negative number (0-exit): 2
*
**
**
*
Enter a non-negative number (0-exit): 1
*
*
Enter a non-negative number (0-exit): 0
If you do not want to use a static variable within the recursive function then instead of it you can apply a trick with standard stream member function width. In this case the recursive function will look the following way
#include <iostream>
#include <iomanip>
void print_stars( size_t n )
{
std::streamsize m = std::cout.width();
if ( m++ != n )
{
std::cout.width( m );
std::cout << std::setfill( '*' );
std::cout << '*' << std::endl;
std::cout.width( m );
print_stars( n );
}
std::cout.width( m-- );
std::cout << std::setfill( '*' );
std::cout << '\n';
}
int main()
{
while ( true )
{
std::cout << "Enter a non-negative number (0-exit): ";
size_t n = 0;
std::cin >> n;
if ( !n ) break;
std::cout << std::endl;
print_stars( n );
std::cout << std::endl;
}
return 0;
}
The output will be the same as above.
P.S. It seems that the only programmer who is able to write the function is me unemployed.:) All others are unable to do this assignment for beginners.:)
I think the best answer should be if only one recursive function is used -
#include <iostream>
using namespace std;
void recursive(int current, int lastEnter, int limit, bool isLimitReached) {
cout << "*";
if(current == lastEnter ) {
cout << endl;
current = 0;
if(isLimitReached == false)
lastEnter++;
else lastEnter--;
}
if(current + 1 == limit) {
isLimitReached = true;
}
current++;
if(!(isLimitReached == true && lastEnter == 0))
recursive(current, lastEnter, limit, isLimitReached);
}
int main()
{
int num = 0;
cout << "Enter max number of stars to be generated : ";
cin >> num;
recursive(1, 1, num, false);
return 0;
}
The code above uses only one recursive function without for/while loops.
output -
Enter max number of stars to be generated : 6
*
**
***
****
*****
******
*****
****
***
**
*
It asks:
Modify the recursive rabbit function so that it is visually easy to follow the flow of execution. In stead of just adding "Enter" and "Leave" messages, indent the trace messages according to how "deep" the current recursive call is.
By exercising correctly adding white space(s) in the recursive rabbit function, better out understanding on how the recursion works.
This is what the program should display:
Enter rabbit: n = 4
Enter rabbit: n = 3
Enter rabbit: n = 2
Leave rabbit: n = 2 value = 1
Enter rabbit: n = 1
Leave rabbit: n = 1 value = 1
Leave rabbit: n = 3 value = 2
Enter rabbit: n = 2
Leave rabbit: n = 2 value = 1
Leave rabbit: n = 4 value = 3
I don't really have a clue to how to get the proper indentations or how to display the "leave rabbits" that have n greater than 2. So far my code is:
#include <iostream>
#include <iomanip>
int rabbit(int);
using namespace std;
int main()
{
cout << rabbit(4) << endl;
return 0;
}
int rabbit(int n)
{
cout << "Enter rabbit: n = " << n << endl;
if(n <=2)
{
cout << "Leave rabbit: n = " << n << endl;
return 1;
}
else
{
return rabbit(n - 1) + rabbit(n - 2);
}
}
Can someone point me to the right direction? Thank you very much.
EDIT:
I have it somewhat close but it is still missing the ability to display "Leave rabbit: n = 3" and "Leave rabbit: n = 4."
Here is my new code:
#include <iostream>
#include <iomanip>
int rabbit(int, int);
using namespace std;
int main()
{
int months;
cout << "How many months?" << endl << "Months ::: ";
cin >> months;
cout << rabbit(months, 0) << endl;
return 0;
}
int rabbit(int n, int parameter)
{
int value;
for(int i = 0; i < parameter; i++)
{
cout << " ";
}
cout << "Enter rabbit: n = " << n << endl;
if(n <=2)
{
for(int i = 0; i < parameter; i++)
{
cout << " ";
}
value = 1;
cout << "Leave rabbit: n = " << n << " value = " << value << endl;
return value;
}
else
{
return rabbit(n - 1, parameter + 1) + rabbit(n - 2, parameter + 1);
}
}
On SO, we try not to give code solutions to assignments, and to your credit you are only asking for hints.
The key to solving any problem is to state it well.
If you look at the required output, you can see
The output from the first call is not indented.
The output from the next call is indented 3 spaces.
The output from the next call is indented 3 more spaces.
So: what is the relationship between the number of level of calls to rabbit, and the amount of indentation?
If there were more, deeper calls to rabbit we would expect a good solution to continue to work, giving greater levels of indentation.
I think you'll kick yourself, all you need to do is use the value variable for both cases.
int rabbit(int n, int parameter)
{
int value;
for(int i = 0; i < parameter; i++)
{
cout << " ";
}
cout << "Enter rabbit: n = " << n << endl;
if(n <=2)
{
value = 1;
}
else
{
value = rabbit(n - 1, parameter + 1) + rabbit(n - 2, parameter + 1);
}
for(int i = 0; i < parameter; i++)
{
cout << " ";
}
cout << "Leave rabbit: n = " << n << " value = " << value << endl;
return value;
}