factorial,,,

hey guys.. i know how to factorial, my problem is how can i do when i used function call...

int main()
{
int n; 
int factorial,i; 

cout << "Enter a positive integer: ";
cin >> n;

	for (i = 0; i <= n; i++)
	
		if (i == 0)
		factorial = 1;
		else
		factorial = factorial * i;
	
	cout << "The factorial of " << n << " is " << factorial << endl;


now, i need to used function call.. what i will do??

thanks for the help!!
you need to put that in a recursive function

1
2
3
inline int Factorial(int x) {
  return (x == 1 ? x : x * Factorial(x - 1));
}


you should probably learn the language syntax/semantics completely first
Last edited on
You should avoid using recursion unless it massively simplifies your problem. It's just a neat way of slowing things down. Don't use that example Diemon, especially if this is homework, because your teacher will definitely know it's not your own code =P

kbw is on the money, this has been answered a million times before, go and find it.
ahaha thanks guys...
It's just a neat way of slowing things down


1
2
3
int factorial(int x, int result = 1) {
  if (x == 1) return result; else return factorial(x - 1, x * result);
}


Ha, my recursion works just as fast as a for/while loop! :P
Last edited on
Ha, my recursion works just as fast as a for/while loop!
How can you be sure of that? What was the size of x used?
By analyzing the generated assembly:

1
2
3
4
5
6
7
8
9
10
11
12
13
_Z9factorialii:
.LFB2:
        jmp     .L7
        .p2align 4,,10
        .p2align 3
.L5:
        imull   %edi, %esi
        subl    $1, %edi
.L7:
        cmpl    $1, %edi
        jne     .L5
        movl    %esi, %eax
        ret


Recursion doesn't slow down anything if you know what you are doing :P
Last edited on
rapidcoder wrote:
Recursion doesn't slow down anything if you know what you are doing :P
Your compiler did tail call optimization. Unfortunately, there is no standardized way to force it. I like recursion. It somehow emphasizes the invariants in the code. But it can cause nasty business in embedded systems with small stack (low-end low-consumption hardware), and is generally not as effective as iteration in non-functional languages.

Regards

Unfortunately, there is no standardized way to force it

True, but this is the limitation of the language/compiler not the recursion per se. Ofc, I don't recommend using recursion in languages that don't have proper way to enforce TCO optimisations. Nevertheless coding in a recursive style is a good brain-excercise. :)
Last edited on
#include <iostream>
int fakt(int n);
using namespace std;

int main ()
{

int m;
int faktoriel;


cout<<"Enter number: ";
cin>>m;

faktoriel=fakt(m);

cout<<"The fac. is: "<<faktoriel<<endl;
cin.get(); cin.get();

return 0;
}

int fakt(int n) {

int fact=1;
int i;

for (i=1; i<=n; i++)
fact*=i;

return fact;
}
now i know.. thanks!! :*
Topic archived. No new replies allowed.