answersLogoWhite

0


Best Answer

There are two ways to implement a factorial function. The first is the conventional method using a constexpr function:

constexpr fct (unsigned n) {

return (i < 2) ? 1 : n * fct (n - 1);

}

This has the advantage in that it can be used for both compile-time and runtime computation:

constexpr unsigned x = fct (5); // compile-time computation

A good compiler will perform the complete calculation at compile-time, thus the declaration of x is equivalent to:

constexpr unsigned x = 120; // e.g. x = 5 * 4 * 3 * 2 * 1

Conversely, the declaration of y is not constexpr, thus the calculation must be performed at runtime. The same is true of any non-const variable.

However, if we only required compile-time computation, then we can use template-metaprogramming instead:

template<unsigned N>

constexpr unsigned fac (void) {

return N*fac<N-1>();

}

template<>

constexpr int fac<2> (void) {

return 2;

}

Note that we cannot use variables in a template intended for compile-time computation, hence we use a template parameter and a specialisation to enable the recursion. The specialisation for N=2 represents the end-point of recursion. We could also provide a specialisation for N=1 and N=0, however this would be superfluous given that fac<1> and fac<0> both equate to 1 and we'd never deliberately invoke these in code.

Note also that the largest integer we can represent with an unsigned integer is UINT_MAX (defined in <limits>). For a 32-bit integer this is (2^32)-1, thus fct<12> is the largest factorial we can calculate. If we use uint64 instead, then we can calculate factorials up to fct<21>. However, the larger the value of N, the less likely we can make use compile-time computation, but we can still make use of partial compile-time computation in conjunction with runtime computation if we use the constexpr version of the function.

If we wish to accommodate larger factorials, then we must either use a long double or use a user-defined type that can handle larger integers, however the latter would mean losing compile-time computation altogether.

User Avatar

Wiki User

7y ago
This answer is:
User Avatar
More answers
User Avatar

Wiki User

12y ago

The most common method of generating a factorial is the recursive method...

/* Microsoft 64 bit recursive */

unsigned long long NFactLongLongRecursive (unsigned long long N) {

if (N < 2) return 1;

if (N 2) {

decimal_initialize (d, 2);

return;

}

while (N > 2) {

decimal_multiply (d, N);

N--;

}

return;

}

/* Example main line */

/* Generates all variations to show differences in results */

int main (int argc, char *argv[]) {

int N;

decimal Decimal = {2, NULL};

if (argc < 2) {

printf ("Enter N (or use command line) : ");

scanf_s ("%d", &N);

} else {

N = atoi (argv[1]);

}

printf ("LongLong: %u! = %u\n", N, NFactLongLongRecursive (N));

/* note: arbitrary is exact - if the others don't match, arithmetic overflow occurred */

printf ("Arbitrary: %u! = ", N);

decimal_NFactIterative (&Decimal, N);

decimal_print_digits (&Decimal, true);

return 0;

}

This answer is:
User Avatar

User Avatar

Wiki User

13y ago

Writing a program to calculate factorials is tricky, because factorials quickly get large enough to overflow the underlying integer data type. Here is an example program that compares several methods, including an arbitrary length decimal type using a linked list that will calculate any factorial, limited only by available stack size. Note that in order to calculate very large values, you will need to tell the linker/binder to increase the run-time stack size from its default value.

// Factorial.cpp : Defines the entry point for the console application.

//

#include <stdlib.h>

#include <stdlib.h>

/* Microsoft 32-bit iterative */

unsigned long NFactLongIterative (unsigned long N) {

unsigned long result = N;

if (N < 2) return 1;

if (N 2) {

decimal_initialize (d, 2);

return;

}

while (N > 2) {

decimal_multiply (d, N);

N--;

}

return;

}

/* Example main line */

/* Generates all variations to show differences in results */

int main (int argc, char *argv[]) {

int N;

decimal Decimal = {2, NULL};

if (argc < 2) {

printf ("Enter N (or use command line) : ");

scanf_s ("%d", &N);

} else {

N = atoi (argv[1]);

}

printf ("Long: %u! = %u\n", N, NFactLongIterative (N));

printf ("LongLong: %u! = %I64u\n", N, NFactLongLongIterative (N));

printf ("Recursive: %u! = %I64u\n", N, NFactLongLongRecursive (N));

printf ("Double: %u! = %.0f\n", N, NFactDouble (N));

/* note: arbitrary is exact - if the others don't match, arithmetic overflow occurred */

printf ("Arbitrary: %u! = ", N);

decimal_NFactIterative (&Decimal, N);

decimal_print_digits (&Decimal, true);

return 0;

}

This answer is:
User Avatar

Add your answer:

Earn +20 pts
Q: How do you write a program in c to get the factorial of a number?
Write your answer...
Submit
Still have questions?
magnify glass
imp
Continue Learning about Engineering

Write a java script program to print first ten odd natural numbers in C?

Q.1 Write a program to print first ten odd natural numbers. Q.2 Write a program to input a number. Print their table. Q.3 Write a function to print a factorial value.


Write a C-like program fragment that calculate the factorial function for argment 12 with do while loop?

#!/usr/bin/perl print factorial($ARGV[11]); sub factorial { my($num) = @_; if($num == 1) { return 1; # stop at 1, factorial doesn't multiply times zero } else { return $num * factorial($num - 1); # call factorial function recursively } }


How do you write a c program to convert binary to decimal by using while statement?

write a c++ program to convert binary number to decimal number by using while statement


How do you create factorial program in qbasic?

since factorial is for example , the factorial of 5 = 5 (5-1)(5-2)(5-3)(5-4) that means the last number to subtract from 5 is 4 , which is (n-1) ie the factorial of any number is (n-0)(.............)(n-(n-1)) to write this , 5 REM to calculate the factorial of any number 6 DIM fac AS INTEGER LET fac = 1 10 INPUT "enter the number to find its factorial "; a ' variable a 15 FOR b = 0 TO (a-1) 'numbers that will be subtracted from the " a" 20 c= a -b 'each number in the factorial calculation 25 fac = fac * c 'to compute each multiplication in the factorial 30 NEXT b 35 PRINT 'to leave a line 40 PRINT fac 45 END note this due to some unattained raesons works for numbers 0 to 7


How do you write a C program to check whether the number is odd or even Ps-using DEV complier?

To write a C program to determine if something is odd or even you need to be a programmer. To write a program in C is complicate and only done by programmers.

Related questions

7 Write a C program to compute the factorial of a number using for loop?

int factorial(int n) { int i; int f=1; for(i=2;i&lt;=n;++i) f*=i; return f; }


Write a java script program to print first ten odd natural numbers in C?

Q.1 Write a program to print first ten odd natural numbers. Q.2 Write a program to input a number. Print their table. Q.3 Write a function to print a factorial value.


1.Write a c program for Fibonacci series?

/*program to calculate factorial of a number*/ #include&lt;stdio.h&gt; #include&lt;conio.h&gt; void main() { long int n; int a=1; clrscr(); printf("enter the number="); scanf("%ld",&amp;n); while(n&gt;0) { a*=n; n--; } printf("the factorial is %ld",a); getch(); }


Write a c program to find the factorial of 125?

int main (void) { puts ("18826771768889260997437677024916008575954036487149242588759823150835\ 31563316135988668829328894959231336464054459300577406301619193413805\ 97818883457558547055524326375565007131770880000000000000000000000000\ 000000"); return 0; }


Write a C-like program fragment that calculate the factorial function for argment 12 with do while loop?

#!/usr/bin/perl print factorial($ARGV[11]); sub factorial { my($num) = @_; if($num == 1) { return 1; # stop at 1, factorial doesn't multiply times zero } else { return $num * factorial($num - 1); # call factorial function recursively } }


What is the logic and theory for pascal triangle program in C?

long factorial(int); int main() { int i, n, c; printf("Enter the number of rows you wish to see in pascal triangle\n"); scanf("%d",&n); for ( i = 0 ; i < n ; i++ ) { for ( c = 0 ; c


Program to find the factorial of a number using recursion?

/*program to find the factorial of a given number*/ #include&lt;stdio.h&gt; #include&lt;conio.h&gt; int fact(int); void main() { int n,c; printf("\n enter the number for which you want to find the factorial"); scanf("%d",&amp;n); c=fact(n); printf("\n the factorial of the number %d is %d",n,fact); getch(); } int fact(int n) { int k; if(n==0) return(1); else k=n*fact(n-1); return(k); }


What is a program in c to calculate factorial of number?

First of all we will define what factorial is and how to it is calculated.Factional is non negative integer. Notation would be n! It is calculated by multiplying all integers from 1 to n;For example:5! = 1 x 2 x 3 x 4 x 5 = 120.Note: 0! = 1Small C program that illustrates how factorial might be counted:#include int factorial(int num);int main() {int num;printf("Enter number: ");scanf("%d", &num);printf("Factorial: %d\n", factorial(num));return 0;}int factorial(int num) {if (num == 0) {return 1;}return num * factorial(num - 1);}Testing:Enter number: 5Factorial: 120Enter number: 0Factorial: 1


How do you write a c program to convert binary to decimal by using while statement?

write a c++ program to convert binary number to decimal number by using while statement


C program to find factorial of a no?

this is a code for calculating it recursivelly: float Factorial (float n) { if (n&lt;=1) return 1.0; else return n* Factorial(n-1); }


How do you create factorial program in qbasic?

since factorial is for example , the factorial of 5 = 5 (5-1)(5-2)(5-3)(5-4) that means the last number to subtract from 5 is 4 , which is (n-1) ie the factorial of any number is (n-0)(.............)(n-(n-1)) to write this , 5 REM to calculate the factorial of any number 6 DIM fac AS INTEGER LET fac = 1 10 INPUT "enter the number to find its factorial "; a ' variable a 15 FOR b = 0 TO (a-1) 'numbers that will be subtracted from the " a" 20 c= a -b 'each number in the factorial calculation 25 fac = fac * c 'to compute each multiplication in the factorial 30 NEXT b 35 PRINT 'to leave a line 40 PRINT fac 45 END note this due to some unattained raesons works for numbers 0 to 7


How do you write a C program to check whether the number is odd or even Ps-using DEV complier?

To write a C program to determine if something is odd or even you need to be a programmer. To write a program in C is complicate and only done by programmers.