Iterative or Recursive Factorial [closed] - c++

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I've implemented factorial recursively this way:
int factorial(int x){
if (x <= 0)
return 1;
else
return (x*factorial(x - 1));
}
int _tmain(int argc, _TCHAR* argv[])
{
std::cout << "Please enter your number :::";
int x;
std::cin >> x;
std::cout<<"factorial(" << x << ") = "<< factorial(x);
getchar(); getchar();
}
which way of implementing such code is more useful writing it using iteration and loops or writing it recursively such as above?

It depends on the number itself.
For normal-range numbers, recursive solution could be used. Since it makes use of previous values to calculate future values, it can provide the value of 'factorial(n-1)' on the fly.
factorial(n) = factorial(n-1) * n
However, since recursion makes use of stacks, it would eventually overflow if your calculation goes deeper than the stack-size. Moreover, recursive solution would give poor performance because of heavy push-pop of the registers in the ill level of each recursive call.
In such cases, iterative approach would be safe.
Have a look at this comparison.
Hope it helps!

In C++ a recursive implementation is usually more expensive than an iterative one.
The reason is that each call causes a creation of a new stack frame which holds data such as return address, local variables and registers that are needed to be saved. Therefore a recursive implementations requires amount of memory which is linear with the depth of your nested calls while iterative implementations use a constant amount of memory.
In your specific case, which is tail recursion, a compiler optimization may switch the function call with a direct jump preventing the unnecessary usage of memory on the call-stack.
For more detailed explanation you might want to read:
Is recursion ever faster than looping?

Related

How to write a factorial calculator that extends to negative numbers? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm trying to write a program for a factorial which tries to calculate as such.
If n is the natural number, then the answer is n*(n-1)(n-2)....1(-1)(-2))(-3)...*(-10)
Here is C++ code which just doesn't go beyond printing n. It works without the if else statement.
#include <iostream>
using namespace std;
int main() {
int val=0, prod=1;
std::cout<<"Enter the number"<<std::endl;
std::cin>>val;
std::cout<<"The number is "<<val<<std::endl;
while(val>=-10)
{
prod=prod*val;
if (val=1)
{
val=val-2;
}
else
{
val=val-1;
}
}
std::cout<<prod<<std::endl;
return 0;
}
if (val=1)
should be
if (val==1)
= for assignment and == for comparison.
I would expect your compiler to warn you about this very common error. If it didn't you should find out why, if it did you should pay attention.
Compiler warnings will save you loads of time in the long run.
Sometimes programming tests are about common sense, like in this one:
You say that you need to calculate:
n*(n-1)*...*1*(-1)*(-2)*...*(-10)
This is the same as (there's an even number of negatives, so it becomes positive):
n*(n-1)*...*1*fact(10) // fact(10)=3,628,800
So, I would just write the function for calculating the factorial of a number and multiply the result by 3,628,800.
Obviously, there might a catch: fact(10) is about three million, while on most computers, the maximum value of int (the basic type you're using) is about two billion, which is not even a thousand times larger than the value you need to multiply with.
So, instead of using a simple int, I'd suggest you to use integer types which can hold larger numbers, like long long or unsigned long long. Maybe this is the real purpose of this exercise?

Why doesn't this code use the C++ power function directly? Can someone help me with the power function in this code? [closed]

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 3 years ago.
Improve this question
This problem is to output a single integer, the number of possible combinations calculated:
int power(int a, int n)
{
if (n == 0)
return 1;
// else
if (n % 2 == 0) {
int temp = power(a, n / 2);
return temp * temp;
}
// else
return a * power(a, n - 1);
}
This function uses a technique called exponentation by squaring.
It's a particularly efficient way of evaluating the power for integral type arguments. The standard C function uses floating point arguments, and the C standard doesn't require an exact result even if the floating point arguments represent whole numbers.
In C++ though you can probably rely on one of the overloads of std::pow that takes integral type arguments, and cast the result, subject to your making the necessary size checks. But again even the C++ standard does not require that the best possible result is returned (cf. std::sqrt under IEEE754), although one could reasonably regard a std::pow function that does not return the correct result for integral arguments to be defective.

Defining variables vs calculating on the fly [closed]

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
In terms of readability and memory usage/ processing speed is it better to define a variable, modify it and output the variable or to just output a result? eg:
int a = 1, b = 2, c;
c = a+b;
std::cout << c << std::endl;
vs
int a = 1, b = 2;
std::cout << a+b << std::endl;
Thanks
Well with this example processing speed and space is negligible. So small and so few instructions.
But in the grand scheme of things the answer is -- well it depends.
The term "better" is in the eye of the beholder. What is better for one program might not be better for another (this includes readability). What may work in one instance may not work in another. Or in the end it could be negligible (arithmetic instructions are pretty fast depending on the scope of what you need and int, double, char, float data types are relatively small and well defined so you know how much memory you are taking up).
Here you do not define if these variables were declared on the stack or the heap. If on the stack then it doesn't matter if you declared it because after the function that these variables live in ends, the memory gets released. If on the heap you may not want to declare millions of variables just to sit there. But then again you may need them there.
So its based almost entirely on a case by case bases when dealing with bigger projects.
And you tell me what is better here?
int result = (3434*234+3423-4/3*23< 233+5435*234+342)? (int)(234+234+234234/34):(int)(2+3*234);
std::cout << result << std::endl;
OR
double x = 3434*234+3423-4/3*23;
double y = 233+5435*234+342;
double a = 234+234+234234/34;
double b = 2+3*234;
int result = 0;
if( x>y) result = a;
else result = b;
std::cout << result << std::endl;
in the end it these do the same things are the same with negligble difference but which one is easier to read?
Your question on memory is easy to answer, variables are stored identifiers so each take a couple bytes (bytes store 8 bits or binary digits) to store. That being said, a byte is almost no memory, meaning that ultimately it has no net effect. In terms of RAM (or Random Access Memory) a byte is again, almost negligible meaning that defining a, b, and c is barely slower than just calculating a + b. Makes sense?

Which of the two programs is better and why? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Code 1
int A, B, MAX;
cout << "Give two numbers:" << endl;
cin >> A >> B;
if (A > B)
{
MAX = A;
}
else
{
MAX = B;
}
cout << "Largest amongst given numbers is: ";
cout << MAX << endl;
return 0;
Code 2
int A, B, MAX;
cout << "Give two numbers:" << endl;
cin >> A >> B;
MAX = A;
if (B > MAX)
{
MAX = B;
}
cout << "Largest amongst given numbers is: ";
cout << MAX << endl;
return 0;
In above program logic, which one is best and why? is there any difference between them.? it is my exam question i would like to ask stack overflow to know best opinion.
MAX = std::max(A, B);
Is better than both in terms of clarity.
In terms of speed, the compiler should be able to optimise any of these methods to be equivalent; but again I'd favour std::max because I'd sooner trust the compiler to optimise a standard function than some arbitrary made up code to perform the same task.
They are the same so I would prefer code 1 because it's more readable. In both cases you have to bring both A and B into a register (regardless) and then do a single comparison (regardless). And it won't write out to the variable MAX until after this segment is done (because it won't need to kick anything out of a register).
This isn't something that is going to cause any kind of performance gain. In fact, it's possible (although I doubt it) that the compiler would compile them the same (the compiler does all kinds of code modification to create an optimal set of instructions).
As suggested the only thing that likely would give a performance gain is using the library function std::max. This is because the compiler will basically perform the comparison in the most efficient way (likely without even calling a conditional jump). If your two values are integers, then you can see here that it's possible to find the max with five integer operations (all of which, except the multiplication can generally be done in a single cycle). You generally want to avoid conditional jumps as much as possible and this algorithm does that. Most likely the max function does something like this or similar (but it would have to be different for floating point values).
After MAX = std::max(A,B), the next best code is:
MAX = A > B ? A : B;
If you don't want to use that, then I prefer your "code 1" because:
code 2 always sets MAX = A, which is momentarily misleading and only becomes clear as the later code is studied; while this issue is common in C++ and many other languages, there's no particular reason to embrace that complication when it's easily avoided
for some types (the question didn't originally specify int), an assignment may be an expensive operation (e.g. copying a lot of data), so always assigning once is better than potentially assigning twice
For both those reasons, it also desirable to declare and define MAX in one step. It may not be practical if say it's a non-const reference accepted as a function argument, but when it is possible it's another good reason to prefer std::max or the ternary ? approach: you won't need a misleading and potentially inefficient or unavailable default construction. (Now you've changed the question to be int specific, the expense of copying and construction is known and trivial, and the optimiser can be counted on to remove them in most cases).
I would say use code 2. It is better because you explicitly say that if MAX B is greater than MAX A, then change MAX to B. In the other one, you don't have any defining factors about why MAX A is greater than MAX B. From what I see, you will probably have a harder time using code 1 than code 2.

Shift operator fast or not fast? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
What is the faster between the two following code? why?
In which case one can be preferred to the other?
double x = (a + b) >> 1
double x = (a + b) / 2.0
These do different things so pick the one with the functionality you like: Truncating the result down or returning the 0.5 fraction.
"Premature optimization is root of all evil". Use what is more readable, when you have perfomance issue first look for algorithms and data structures, where you can get most perfomance gain, then run profiler and optimize where is necessary.
As others have said, the two statements produce different results, especially if (a + b) is an odd value.
Also, according to the language, a and b must be integral values in order to satisfy the shifting operation.
If a and b differ in type between the two statements, you are comparing apples to elephants.
Given this demo program:
#include <iostream>
#include <cstdlib>
#include <cmath>
using std::cout;
using std::endl;
int main(void)
{
const unsigned int a = 5;
const unsigned int b = 8;
double x = (a + b) >> 1;
cout << x << endl;
double y = (a + b) / 2.0;
cout << y << endl;
return EXIT_SUCCESS;
}
The output:
6
6.5
Based on this experiment, the comparison is apples to oranges. The statement involving shifting is a different operation that dividing by a floating point number.
As far as speed goes, the second statement is slower because the expression (a + b) must be converted to double before applying the division. The division is floating point, which may be slow on platforms without hardware floating point support.
You should not concern yourself on the execution speed of either statement. Of more importance is the correctness and robustness of the program. For example, the two statements above provide different results, which is a very important concern for correctness.
Most Users would wait for a program to produce correct results than have a quick program producing incorrect results or behavior (nobody is in a hurry for a program to crash).
Management would rather you spend time completing the program than wasting time optimizing portions of the program that are executed infrequently.
If a or b is a double or float, shifting will produce incorrect results.