In my program,user will be asked for 2 different options.
I chose option 2..iterative and key in any value which will then lead to the output.
However,when i choose the 1st option which is recursive,it wont output anything that its value is above 30.Meaning to say,you will see an output if key in a value of 30..& there will be no output if were to key in the value of 40 or 50.
Can anyone please test on your compiler too?Its ok if something wrong with my compiler but if there is something wrong with my code.
#include<iostream>
using namespace std;
/* Fibonacci: recursive version */
int Fibonacci_R(int n)
{
if (n <= 0) return 0;
else if (n == 1) return 1;
else return Fibonacci_R(n - 1) + Fibonacci_R(n - 2);
}
// iterative version
int Fibonacci_I(int n)
{
int fib[] = { 0, 1, 1 };
for (int i = 2; i <= n; i++)
{
fib[i % 3] = fib[(i - 1) % 3] + fib[(i - 2) % 3];
cout << "fib(" << i << ") = " << fib[i % 3] << endl;
}
return fib[n % 3];
}
int main()
{
int a, opt;
cout << "Please choose the available option:\n";
cout << "1)Recursive\n";
cout << "2)Iterative\n";
cin >> opt;
if (opt == 1)
{
cout << "Please input value:\n";
cin >> a;
Fibonacci_R(a);
cout << endl << "From recursive function" << endl;
for (int i = 1; i <= a; ++i)
cout << "fib(" << i << ") = " << Fibonacci_R(i) << endl;
cout << endl;
}
else
if (opt == 2)
{
cout << "Please input value:\n";
cin >> a;
Fibonacci_I(a);
}
system("pause");
return 0;
}
When implementing an algorithm, I like to mentally evaluate the algorithm, to see what the computer is doing.
fib(30)
= fib(29) + fib(28)
= fib(28) + fib(27) + fib(27) + fib(26)
= fib(27) + fib(26) + fib(26) + fib(25)+ fib(26)+ fib(25) + fib(25)+ fib(24)
I notice that this algorithm seems really really inefficient.
To calculate fib(30) it require 2^30 calculations! That's 1073741824!
Even worse, if I increase the number by 1, the time/operations to get a result doubles!
It will probably run forever with a large enough number! (Well until I fall asleep or my CPU burns up atleast)
Optimization
However, I notice that a lot of the calculations are redundant. To calculate fib(30), it must calculate fib(29) and fib(28). To calculate fib(29), it calculates fib(28) again. So inefficient!
When I see these kind of calculations the first thing that springs to mind is a technique call memoization. It caches results from a previous calculation and stores them for later use.
Using that in this case will reduce the number of calculations to something around 60 operations (?) at the cost of using more memory.
Example: What is memoization and how can I use it in Python?
It is not stuck, it just takes too long. It is because the complexity of recursive calculation. I assume that this school example was meant to show why recursive approach is inferior most of the time and should not be used.
Suppose you want to calculate Fibonacci_R(10). You will need to call Fibonacci_R(8) and Fibonacci_R(9). For calculation of Fibonacci_R(9) you will need to call Fibonacci_R(8) and Fibonacci_R(7). Which means you are calling Fibonacci_R(8) twice. If you continue along you will find that you are calling Fibonacci_R(7) three times - two times for Fibonacci_R(8) and once for Fibonacci_R(9)... you call Fibonacci_R(6) five times - two times for Fibonacci_R(8) and three times for Fibonacci_R(7)... etc. This is really hard when you start not with 10 but with 30. This will make your processor burn if you increase the number even more. Do not try it at home or make sure you have fire extinguisher at hand.
Btw. recursive algorithm is usually inferior not because of the complexity but because of limited memory stack which is used to store the variable and return address when calling a function.
A condition needed to be set for
"int a"
so while true, the "Fibunacci_R" function could execute. So;
I used a "do/while" condition/loop at the point where "Fibunacci_R" is called and it worked
#include <iostream>
using namespace std;
/* Fibonacci: recursive version */
int Fibonacci_R(int n)
{
if (n <= 0) return 0;
else if (n == 1) return 1;
else return (Fibonacci_R(n - 1) + Fibonacci_R(n - 2));
}
// iterative version
int Fibonacci_I(int n)
{
int fib[] = { 0, 1, 1 };
for (int i = 2; i <= n; i++)
{
fib[i % 3] = fib[(i - 1) % 3] + fib[(i - 2) % 3];
cout << "fib(" << i << ") = " << fib[i % 3] << endl;
}
return fib[n % 3];
}
int main() {
int a, opt;
cout << "Please choose the available option:\n";
cout << "1)Recursive\n";
cout << "2)Iterative\n";
cin >> opt;
if (opt == 1) {
cout << "Please input value:\n";
cin >> a;
// Here
do {
cout << endl << "From recursive function" << endl;
for (int i = 1; i <= a; ++i)
cout << "fib(" << i << ") = " << Fibonacci_R(i) << endl;
cout << endl;
break;
} while (Fibonacci_R(a));
}
else
if (opt == 2)
{
cout << "Please input value:\n";
cin >> a;
Fibonacci_I(a);
}
system("pause");
return 0;
}
It just takes an awful lot of time to calculate an input of integers greater than 45
Related
Trying to make a calculator that calculates values in an array based on input from user. But the first value in the array is always 0 when I leave 'p undefined or p = 1 will have give me the same problem. It should be whatever the user enters for the first value and so on.
#include <iostream>
using namespace std;
int main() {
double x;
int p = 1, y = 0;
double sum = 1;
int many[p];
char op;
cout << "How many numbers are you working with today?" << endl;
cin >> x;
do
{
if (y > x)
break;
cout << "Enter number " << y + 1 << ":" << endl;
cin >> many[p];
cout << "What would you like the numbers to do: (+ - / *)" << endl;
cin >> op;
if (op == '+')
{
sum+=many[p];
cout << sum <<endl;
}
else if (op == '-')
{
sum-=many[p];
cout << sum <<endl;
}
else if (op == '*')
{
sum*=many[p];
cout << sum <<endl;
}
else if (op == '/')
{
sum/=many[p];
cout << sum <<endl;
}
else {cout << "ERROR: Enter correct value." << endl;}
y++;
}
while (y < x);
}
The sum should be 3 not 4.
How many numbers are you working with today?
2
Enter number 1:
1
What would you like the numbers to do: (+ - / *)
+
Enter number 2:
2
What would you like the numbers to do: (+ - / *)
+
4
The program is invalid and has undefined behavior.
For starters variable length arrays is not a standard C+ feature
int p = 1, y = 0;
double sum = 1;
int many[p];
And in any case you defined an array with one element. So the only valid index to access elements of the array is 0.
Even in the first statement that uses the array
cin >> many[p];
it is accessed outside its bounds.
You should use the standard class template std::vector. Or as in fact you are dealing with one value then there is even no sense to use a container, Define a scalar object instead of the array.
The initial value of the sum is 1, that's why it is adding 1 more. We can't keep it 0 either, because then it will mess up the '*' and '/' cases.
I have added the initial sum value for all the cases.
Also, I would suggest you, to use switch cases instead of if, else statements.
#include <iostream>
using namespace std;
int main() {
double x;
int p = 1, y = 0;
double sum = 1;
int many[p];
char op;
cout << "How many numbers are you working with today?" << endl;
cin >> x;
do
{
if (y > x)
break;
cout << "Enter number " << y + 1 << ":" << endl;
cin >> many[p];
cout << "What would you like the numbers to do: (+ - / *)" << endl;
cin >> op;
if (op == '+')
{
if (y == 0) {
sum = 0;
}
sum+=many[p];
cout << sum <<endl;
}
else if (op == '-')
{
if (y == 0) {
sum = 0;
}
sum-=many[p];
cout << sum <<endl;
}
else if (op == '*')
{
if (y == 0) {
sum = 1;
}
sum*=many[p];
cout << sum <<endl;
}
else if (op == '/')
{
if (y == 0) {
sum = 1;
}
sum/=many[p];
cout << sum <<endl;
}
else {cout << "ERROR: Enter correct value." << endl;}
y++;
}
while (y < x);
}
There are a lot of things here that don't make sense.
You are starting with sum = 1. this is why the value is always +1
many is an array of size 1, can be changed to single int.
you are accessing many[p] which is many[1] which is out of bounds. you can only access many[0]
the rest I leave it to you to find,
Problem is with the if statment inside the while loop. It is not printing the desired output. The else if statement and the else statement seem to work fine
Any help is appreciated
#include <iostream>
using namespace std;
/*
Write a C++ program that asks the user for an integer.
The program finds and displays the first power of 3
larger than the input number using while
*/
int main() {
int input = 0;
int base = 3;
int exponent = 0;
int sum = 1;
cout << "Enter a number: ";
cin >> input;
while (sum < input) {
// This is the if statement giving me problems
if (input == 1) {
exponent += 1;
sum = 3;
}
// This else if statement seems to work fine
else if (input == 3) {
exponent += 2;
sum = 9;
}
else {
exponent++;
sum *= base;
}
}
// Print output
cout << "3 to the power of " << exponent << " is equal to " << sum;
cout << endl << "It is the first power of 3 larger than " << input;
return 0;
}
Your logic is wrong (and I have to say a bit bizarre).
If the input is 1 then while (sum < input) is not true and so you never reach your if (input == 1) statement.
REALIZED my mistake. i just moved the if and else if statement to outside the loop
#include <iostream>
using namespace std;
/*
Write a C++ program that asks the user for an integer.
The program finds and displays the first power of 3
larger than the input number using while
*/
int main() {
int input = 0;
int base = 3;
int exponent = 0;
int sum = 1;
cout << "Enter a number: ";
cin >> input;
if (input == 1) {
exponent += 1;
sum = 3;
}
else if (input == 3) {
exponent += 2;
sum = 9;
}
while (sum < input) {
exponent++;
sum *= base;
}
cout << "3 to the power of " << exponent << " is equal to " << sum;
cout << endl << "It is the first power of 3 larger than " << input;
return 0;
}
If I understood the objective right from the comments, if conditions are not required. Just replace the condition and simplify the while loop as follows:
while (sum <= input) {
exponent++;
sum *= base;
}
Write a C++ program that asks the user for an integer. The program
finds and displays the first power of 3 larger than the input number
using while
You should probably calculate the answer instead of looping.
#include <iostream>
#include <cmath>
int main() {
int input;
std::cout << "input: ";
std::cin >> input;
int x = 0;
/*
3^x == input
ln(3^x) == ln(input)
x*ln(3) == ln(input)
x == ln(input)/ln(3)
*/
// calculate x = ln(input)/ln(3), round down and add 1
if(input > 0) x = std::floor(std::log(input) / std::log(3.)) + 1.;
std::cout << "answer: 3^" << x << " == " << std::pow(3, x) << "\n";
}
So I wrote a program that utilizes the euclid algorithm to find GCD's of 2 ints.
The user enters one int (n), then the program takes every possible integer combination between 8 and n, finds their respective GCD's (recursively), and prints which GCD calculations required the most modulus operations.
I got the program working, but I get a stack overflow at around n=50, and it needs to work to at least 3000.
I've reviewed my code for a while and cannot find the problem.
#include<iostream>
#include <math.h>
using namespace std;
int cost, gcd, greatestCost, n, beginningA, beginningB, finalA, finalB, finalGCD, iteration;
void findGCD(int num1, int num2, int startingCost) {
//findGCD
//finds GCD of every combination (a,b) from i to n
//prints those with the greatest number of modulus operations
int a = num1;
int b = num2;
cost = startingCost;
cost++;
if (b%a > 0) {
//cout << "gcd(" << b << "," << a << ") = ";
findGCD(b%a, a, cost);
}
else {
gcd = a;
if (cost > greatestCost) {
greatestCost = cost;
finalA = beginningA;
finalB = beginningB;
finalGCD = gcd;
}
//cout << "gcd(" << b << "," << a << ") = " << gcd << " With a cost of: " << cost << endl;
//do next iteration (2,8), (3,8) etc...
if (++beginningA <= beginningB) { //beginning A goes from 1-i first
findGCD(beginningA, beginningB, 0);
}
else {
if (beginningA <= n) { //begin next cycle with new b value (1,9), (2,9) while b <= n
beginningA = 1; //reset to 1 so it will increment from 1-i again
cout << "At i=" << iteration++ << "; gcd(" << finalA << "," << finalB << ") = " << finalGCD <<
" took " << greatestCost << " modulus operations" << endl;
findGCD(beginningA, ++beginningB, 0);
}
else //When it tries to continue iterating with a number > n
//print the last, most intensive, iteration and stop
cout << "At i=" << iteration++ << "; gcd(" << finalA << "," << finalB << ") = " << finalGCD <<
" took " << greatestCost << " modulus operations" << endl;
}
}
}
int main() {
greatestCost = 0; //cost of the iteration with the most modulus operations
beginningA = 1;
beginningB = 8;
iteration = 8;
cout << "Enter an integer greater than 8 " << endl; //receive n from user
cin >> n;
if (n <= beginningB) //begin GCD search, granted user input > 8
cout << "Error!!! integer must be greater than 8";
else
findGCD(beginningA, beginningB, 0); //algorithm begins at (1,8)
return 0;
}
At this point the only thing I can think of as the problem is something I've done in C++ that I shouldn't (I am new to C++ and transferred over from java)
Sample Output
Things I've tried:
splitting the gcd function into 2
passing only references through the functions
First of all your explanation is unclear, from you code I understood that for every 8<=i<=n you take all possible x, y where y<=i and x<=y and calculate which gcd require most steps.
I've rewritten your code so that findGCD only finds gcd of 2 number, while incrementing some global cost variable.
#include<iostream>
#include <math.h>
using namespace std;
int cost, gcd, greatestCost, n, beginningA, beginningB, finalA, finalB, finalGCD, iteration;
int findGCD(int a, int b) {
cost++;
if (b%a > 0)
return findGCD(b%a, a);
else
return a;
}
int main() {
greatestCost = 0; //cost of the iteration with the most modulus operations
beginningA = 1;
beginningB = 8;
iteration = 8;
cout << "Enter an integer greater than 8 " << endl; //receive n from user
cin >> n;
if (n <= beginningB) //begin GCD search, granted user input > 8
cout << "Error!!! integer must be greater than 8";
else {
for ( int i = beginningB; i <= n; i++ ) {
int greatestCost = 0, gcd0 = 1, i0 = 0, j0 = 0;
for ( int t = beginningB; t <= i; t++ )
for ( int j = 1; j <= t; j++ ) {
cost = 0;
int gcd = findGCD(j, t);
if ( cost > greatestCost ) {
greatestCost = cost;
gcd0 = gcd;
i0 = t;
j0 = j;
}
}
cout << "At i=" << i << "; gcd(" << j0 << "," << i0 << ") = " << gcd0 <<
" took " << greatestCost << " modulus operations" << endl;
}
}
return 0;
}
The stack overflow you're getting is caused by using too deeply recursive calls: Every time you call a function a new stack frame (holding local variables, parameters and possibly other stuff) is created in the (call) stack. This frame is freed only when returning (normally or via exception) from the function. But with recursive calls you don't return from the first function call before returning from the second, which in turn only returns after the third and so on. Thus stack frames are piling up on the stack, which is commonly about the size of around 8 kB, until all available memory for the stack is used: That's the stack overflow (you put too much on it, thus it overflows).
This can be solved by using iteration (using loops) instead:
An outer one incrementing from 8 up to the user supplied maximum, as well as an inner one incrementing from 0 to the value of the outer loop's current iteration variable. This gives you all the pairs of values you want to operate on.
Calculating the greatest common divisor and its cost should be factored out into a function.
The only thing left is calling that function from within the loops and some how keeping track of the maximum.
#include <iostream>
#include <vector>
#include <utility>
using namespace std;
unsigned gcd(unsigned a, unsigned b, unsigned * const cost) {
if (cost) {
*cost = 0;
}
while (b != 0) {
auto const rest = a % b;
if (cost) {
++(*cost);
}
a = b;
b = rest;
}
return a;
}
int main() {
unsigned const n = 3500;
unsigned greatestCost = 0;
vector<pair<unsigned, unsigned>> pairs;
for (unsigned b = 8; b <= n; ++b) {
for (unsigned a = 0; a <= b; ++a) {
unsigned cost;
gcd(a, b, &cost);
if (cost == greatestCost) {
pairs.emplace_back(a, b);
} else if (cost > greatestCost) {
pairs.clear();
pairs.emplace_back(a, b);
greatestCost = cost;
}
}
}
cout << "Greatest cost is " << greatestCost << " when calculating the GCD of " << endl;
for (auto const & p : pairs) {
cout << "(" << p.first << ", " << p.second << ")" << endl;
}
return 0;
}
(Live)
Note in particular that I'm not using any global variable.
The above might make you feel that recursion is an unusable, useless construct. This is not the case. Many algorithms are most cleanly expressed using recursion. When putting the recursive call as the last statement, then an optimisation known as tail call optimisation can be used: Then the called function is reusing the stack frame of the calling function, thus not using any more memory.
Unfortunately this optimisation is quite tricky to implement in a language like C++ due to various reasons.
Other languages, mostly functional ones, use it and thus also recursion instead of loops, though. An example of such a language is Scheme, which even requires implementations to be able to make that aforementioned optimisation.
As a final note: You could implement the GCD calculation using recursive calls here, since as you see the maximum depth will be 17 + 1 which should be small enough to fit on any (outside of embedded systems) call stack. I'd still go with the iterative version though: It has better performance, better fits the idiom of the language and is the "safer" way to go.
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;
}
}
I am solving the following simple problem(on one of OnlineJugde sites which is in Russian, so I won't give a link here:). It is easier to state the problem via an example than definition.
Input:
10 // this is N, the number of the integers to follow
1 1 1 2 2 3 3 1 4 4
Output:
3 times 1.
2 times 2.
2 times 3.
1 times 1.
2 times 4.
Constraints:
All the numbers in the input(including N) are positive integer less than 10000.
Here is the code I got Accepted with:
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int prevNumber = -1;
int currentCount = 0;
int currentNumber;
while(n --> 0) // do n times
{
cin >> currentNumber;
if(currentNumber != prevNumber)
{
if(currentCount != 0) //we don't print this first time
{
cout << currentCount << " times " << prevNumber << "." << endl;
}
prevNumber = currentNumber;
currentCount = 1;
}
else //if(currentNumber == prevNumber)
{
++currentCount;
}
}
cout << currentCount << " times " << prevNumber << "." << endl;
}
Now here's my problem. A little voice inside me keeps telling me that I am doing this line two times:
cout << currentCount << " times " << prevNumber << "." << endl;
I told that voice inside me that it might be possible to avoid printing separately in the end. It told me that there would then be perhaps way too many if's and else's for such a simple problem. Now, I don't want to make the code shorter. Nor do I want do minimize the number of if's and else's. But I do want to get rid of the special printing in the end of the loop without making the code more complicated.
I really believe this simple problem can be solved with simpler code than mine is. Hope I was clear and the question won't be deemed as not constructive :)
Thanks in advance.
i came up with this. no code duplication, but slightly less readable. Using vector just for convenience of testing
EDIT my answer assumes you know the numbers ahead of time and not processing them on the fly
vector<int> numbers;
numbers.push_back(1);
numbers.push_back(1);
numbers.push_back(1);
numbers.push_back(2);
numbers.push_back(2);
numbers.push_back(3);
numbers.push_back(3);
numbers.push_back(1);
numbers.push_back(4);
numbers.push_back(4);
for (int i=0; i<numbers.size(); i++)
{
int count = 1;
for (int j=i+1; j<numbers.size() && numbers[i] == numbers[j]; i++, j++)
{
count++;
}
cout << count << " times " << numbers[i] << "." << endl;
}
My version: reading the first value as a special case instead.
#include <iostream>
int main()
{
int n;
std::cin >> n;
int value;
std::cin >> value;
--n;
while (n >= 0) {
int count = 1;
int previous = value;
while (n --> 0 && std::cin >> value && value == previous) {
++count;
}
std::cout << count << " times " << previous << ".\n";
}
}
Run your loop one longer (>= 0 instead of > 0), and in the last round, instead of reading currentNumber from cin, do currentNumber = lastNumber + 1 (so that it's guaranteed to differ).
slightly more CREATIVE answer, this one does not make assumption about input being all known before the start of the loop. This prints the total every time, but makes use of \r carriage return but not line feed. A new line is inserted when a different number is detected.
int prev_number = -1;
int current_number;
int count = 0;
for (int i=0; i<numbers.size(); i++)
{
current_number = numbers[i];
if (current_number != prev_number)
{
count = 0;
cout << endl;
}
count++;
prev_number = current_number;
cout << count << " times " << numbers[i] << "." << "\r";
}
only problem is that the cursor is left on the last line. you may need to append cout << endl;
I think this will work:
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int prevNumber = -1;
int currentCount = 0;
int currentNumber;
int i = 0;
while(i <= n)
{
if(i != n) cin >> currentNumber;
if(currentNumber != prevNumber || i == n)
{
if(currentCount != 0)
{
cout << currentCount << " times " << prevNumber << "." << endl;
}
prevNumber = currentNumber;
currentCount = 1;
}
else
{
++currentCount;
}
i++;
}
}
I would use a for loop, but I wanted to stay as close to the original as possible.