C/C++ Factorial code

In mathematics, the factorial (faktorial) of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example,

5 ! = 5 \times 4 \times 3 \times 2 \times 1 = 120 \

The value of 0! is 1, according to the convention for an empty product. I will create a C factorial code (faktorial code). We can use command :

factorial number_1 number_2

This factorial code (faktorial code) must have two input number. So, program factorial will compute factorial value from number_1 to number_2. Output from this factorial code is in integer, So, maximum output factorial from this code is 2147483648 (maximum signed integer). You can change output from integer to double if you want to compute another big number (maximum double 2.2E+308).

Save this code with name factorial.cpp :

#include <stdio.h>
#include <stdlib.h>

int factorial(int bound1, int bound2);
int main(int argc, char **argv)
{
	int bound1, bound2;
	int vfact;

	if(argc!=3) {
		printf("usage: factorial boundaryI boundaryII \n");
		return(0);
	}

	sscanf(argv[1], "%i", &bound1); //get bound1
	sscanf(argv[2], "%i", &bound2); //get bound2

	printf("factorial from %i to %i \n", bound1, bound2);

	if( (bound1<0) || (bound2<0) ) {
		printf("input bound1 and bound2 must be >= 0 \n");
		return(0);
	}

	if(bound1>bound2) {
		printf("bound1 must be >= bound2 \n");
		return(0);
	}

	vfact = factorial(bound1, bound2);  //get factorial value
	printf("factorial value = %i \n", vfact); //display output factorial
	return(1);
}

int factorial(int bound1, int bound2)
{
	int i;
	int vfact;

	if(bound1==0) bound1=1;
	if(bound2==0) bound2=1;

	vfact = 1;
	for(i=bound1; i<=bound2; i++)  //loop to get factorial value
		vfact *= i;

	return(vfact);
}

Compile this code with command :

gcc factorial.cpp -o factorial

This is output from this factorial code (faktorial code) :

$ ./factorial 5 10
factorial from 5 to 10
factorial value = 151200

 

One Comment

Add a Comment

Your email address will not be published. Required fields are marked *

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.