Thursday, July 30, 2009

C++ question - really a maths one??

I need to calculate the factorial of n (ie n!) I need to write c++ code to work out the factorial of a given value of n ...... can't quite get my head around it..... any suggestions.





I know that what a factorial is, but how do I make a program calculate it depending on the value of n that is inputted?

C++ question - really a maths one??
What do you need to calculate factorial of some number with pen and paper?


Start from 1, then multiply it by 2, then multiply the result by 3, then ... and so on until you multiply it by "n", right?


Program can work the same way.


Declare two variables: one is current_multiplier and other is an obtained_total. Set their initial values. Then perform the standard_procedure ( multiply obtained_total by current_multiplier, increase current_multiplier by one) while current_multiplier is less or equal to n. Voila.
Reply:#include %26lt;iostream.h%26gt;


#include %26lt;conio.h%26gt;





int factorial(int);





void main(void) {


int number;


clrscr();





cout %26lt;%26lt; "Please enter a positive integer: ";


cin %26gt;%26gt; number;


if (number %26lt; 0)


cout %26lt;%26lt; "That is not a positive integer.\n";


else


cout %26lt;%26lt; number %26lt;%26lt; " factorial is: " %26lt;%26lt; factorial(number) %26lt;%26lt; endl;


getch();


}





int factorial(int number) {


int temp;





if(number %26lt;= 1) return 1;





temp = number * factorial(number - 1);


return temp;


}
Reply:#include%26lt;iostream.h%26gt;


void main()


{


int i,n,fact;


cout%26lt;%26lt;"\n Enter the value of n :";


cin%26gt;%26gt;n;


fact=n;


for(i=n;i%26gt;0;i--)


{


fact=fact*(fact-1);


}


cout%26lt;%26lt;"\n Factorial of" %26lt;%26lt;n "is : " %26lt;%26lt;fact;


}
Reply:Use recursive function to do this.
Reply:Depending on what you need, you may take advantage of templates: http://aszt.inf.elte.hu/~gsd/halado_cpp/... (scroll down to where it says factorial function).
Reply:Use Recursion


This is an example of the function:-





unsigned long factorial (unsigned long number)


{


if (number %26lt;= 1)


return 1;


else


return number * factorial(number - 1);


}


No comments:

Post a Comment