Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<stdlib.h>
- #define MAX 375 //factorial of 200 has 375 digits
- /*
- Name : Rasesh Mori
- Roll : 201105518
- Assignment : 0
- Input : Number for which factorial is to be found (0<=n<=200)
- Ouput : Factorial of the input number
- Description : Case 1: input<9(i.e. factorial value can be stored in integer variable)
- * Find factorial by multiplying all the numbers till the number
- Case 2: input>=9
- * Store the result in an array such that each array variable stores one digit of output and simulate multiplication
- */
- int main()
- {
- int factorialNum=1; //number of which factorial is to be found
- int counter;
- int factorialValue; //stores result if can be accomodated in integer range
- int factArray[MAX]; //stores factorial of large numbers
- int index;
- int carry = 0; //used to store carry for multiplication in array
- int arrayValue; //temporary storage of calculation
- int prefixZeroFlag = 1; //used while printing final answer to remove initial zeroes
- //Get input
- printf("\n Enter number for which factorial is to be found: ");
- if(scanf("%d",&factorialNum) == 0)
- {
- printf("\n\nInvalid input: Please enter an integer in range [0-200]\n\n");
- return 1;
- }
- //Check for correctness of input
- if(factorialNum < 0)
- {
- printf("\n\nFactorial for negative number is undefined.\n\n");
- return 1;
- }
- else if(factorialNum > 200)
- {
- printf("\n\nSorry. This program is designed to find factorial for numbers <= 200.\n\n");
- return 1;
- }
- //If result can be accomodated in integer, use traditional method.
- if(factorialNum < 9)
- {
- factorialValue = 1;
- for(counter = 1; counter <= factorialNum; counter++)
- {
- factorialValue *= counter;
- }
- printf("\nFactorial of %d is: %d",factorialNum, factorialValue);
- }
- else //Perform multiplication storing each digit in array
- {
- index=MAX-1;
- factArray[index] = 1;
- //initialize array to 0
- for(counter=0; counter < MAX-1; counter++)
- {
- factArray[counter]=0;
- }
- for(counter=2; counter<=factorialNum; counter++)
- {
- while(index>=0)
- {
- arrayValue = factArray[index] * counter + carry; //Perform multiplication adding previous carry, of any
- carry=0;
- if(arrayValue <= 9)
- {
- factArray[index] = arrayValue;
- } //If result >9, calculate carry and use in next mul.
- else
- {
- factArray[index] = arrayValue % 10;
- carry = arrayValue / 10;
- }
- index--;
- }
- carry=0;
- arrayValue=0;
- index=MAX-1;
- }
- printf("\nFactorial of %d is: ",factorialNum);
- for(index=0;index<MAX;index++) //Printing result
- {
- if(factArray[index]==0 && prefixZeroFlag)
- continue;
- else
- {
- prefixZeroFlag=0;
- printf("%d",factArray[index]);
- }
- }
- }
- printf("\n\n");
- return 0;
- }
Add Comment
Please, Sign In to add comment