×

Factorial Program in C++

C++ Factorial Program:

The product of all positive descending integers is the factorial of n. n! denotes the factorial of n. For instance:

5! = 5*4*3*2*1=120
4! = 4*3*2*1=24

In Combinations and Permutations, the factorial is commonly utilized (mathematics). The factorial program may be written in a variety of ways in C++. Let's look at the three different approaches to create a factorial program.

  • Looping Factorial Program
  • Recursive factorial program

Looping Factorial Program in C++:

#include <iostream> 
#include <stdlib>
#include <bits/stdc++.h> 
using namespace std;  
int main()  
{  
   int i,factorial=1,number;    
  cout<<"enter any Number: ";    
 cin>>number;    
  for(i=1;i<=number;i++){    
  factorial=factorial*i;    
  }    
  cout<<"Factorial of " <<number<<" is: "<<fact<<endl;  
  return 0;  
}  

OUTPUT:

Enter any Number: 4  
Factorial of 4 is:  24
………………………………
Process executed in 1.212 seconds
Press any key continue.

Explanation

In the above program in C++, we are iterating in for loop and signing factorial multiply by the number itself.

Let's look at a recursive factorial program in C++.

#include<iostream> 
#include<bits/stdc++.h>
#include<stdlib>   
using namespace std;      
int main()    
{    
int factorial(int);    
int fact,value;    
cout<<"enter any number: ";    
cin>>value;    
fact=factorial(value);    
cout<<"Factorial of a number is: "<<fact<<endl;    
return 0;    
}    
int factorial(int i)    
{    
if(i<0)    
return(-1); /*Wrong value*/      
if(i==0)    
return(1);  /*Terminating condition*/    
else    
{    
return(i*factorial(i-1));        
}    
}  

OUTPUT:

Enter any number: 8
Factorial of a number is: 40320
……………………………………………….
Process executed in 1.11 seconds
Press any key to continue.

Explanation

In the above program in C++, we have used a recursive version to find the factorial of the given number. In the return statement we are making call to factorial function recursively.

Using while loop for finding the factorial of a number in C++:

// C++ program for factorial of a number
#include <iostream>
#include <bits/stdc++.h>
#include <stdlib>
using namespace std; 
// function to find factorial of given
// number using while loop
unsigned int factorial(unsigned int a)
{
	if(a == 0)
		return 1;
	int x = a, fact = 1;
	while (a / x != a) {
		fact = fact * x;
		x--;
	}
	return fact;
}
// Driver code
int main()
{
	int num = 5;
	cout << "Factorial of "
		<< num << " is "
		<< factorial(num) << endl;
	return 0;
}

OUTPUT:

Factorial of 8 is 40302
………………………………...
Process Executed in 0.1212 seconds
Press nay key to continue.

Explanation

In the above program in C++, we are using loops for finding out the factorial. In the line number eleven we are using while loop for finding out the factorial.

Let us see the factorial of a large number in C++:

// C++ program to compute factorial of big numbers
#include<iostream>
#include<bits/sdtc++.h>
#include<stdlib>
using namespace std; 
// Maximum number of digits in output
#define MAX 500


int multiply(int a, int res[], int res_size); 
// This function finds factorial of large numbers
// and prints them
void factorial(int n)
{
	int res[MAX]; 
	// Initialize result
	res[0] = 1;
	int res_size = 1; 
	// Apply simple factorial formula n! = 1 * 2 * 3 * 4...*n
	for (int a=2; a<=n; a++)
		res_size = multiply(a, res, res_size); 
	cout << "Factorial of given number is \n";
	for (int b=res_size-1; b>=0; b--)
		cout << res[b];
}
// This function multiplies x with the number
// represented by res[].
// res_size is size of res[] or number of digits in the
// number represented by res[]. This function uses simple
// school mathematics for multiplication.
// This function may value of res_size and returns the
// new value of res_size
int multiply(int a, int res[], int res_size)
{
	int carry = 0; // Initialize carry
	// One by one multiply n with individual digits of res[]
	for (int b=0; b<res_size; b++)
	{
		int prod = res[b] * a + carry; 
		// Store last digit of 'prod' in res[]
		res[b] = prod % 10; 
		// Put rest in carry
		carry = prod/10;
	}
	// Put carry in res and increase result size
	while (carry)
	{
		res[res_size] = carry%10;
		carry = carry/10;
		res_size++;
	}
	return res_size;
}
// Driver program
int main()
{
	factorial(200);
	return 0;
}

OUTPUT:

Factorial of given number is
788657867364790503552363213932185062295135977687173263294742533244359449963403342920304284011984623904177212138919638830257642790242637105061926624952829931113462857270763317237396988943922445621451664240254033291864131227428294853277524242407573903240321257405579568660226031904170324062351700858796178922222789623703897374720000000000000000000000000000000000000000000000000
--------------------------------
Process exited after 0.07152 seconds with return value 0
Press any key to continue . . 

Explanation

In the above program in C++, factorial function takes n as parameter in that we are applying simple factorial formula and in the multiply function what we doing is One by one multiplying n with individual digits of res [].

Let us see another method of linked list to find the factorial:

#include <bits/stdc++.h>
using namespace std;
#define rep(i, a, b) for (int i = a; i <= b; i++)
using namespace std;
class Node {
public:
	int data;
	Node* prev;
	Node(int n)
	{
		data = n;
		prev = NULL;
	}
};
void Multiply(Node* tail, int n)
{
	Node *temp = tail,
		*prevNode = tail; // Temp variable for keeping tail
	int carry = 0;
	while (temp != NULL) {
		int data = temp->data * n + carry;
		temp->data = data % 10; // stores the last digit
		carry = data / 10;
		prevNode = temp;
		temp = temp->prev; // Moving temp by 1 prevNode will
						// now denote temp
	}
	// If carry is greater than 0 then we create another
	// node for it.
	while (carry != 0) {
		prevNode->prev = new Node((int)(carry % 10));
		carry /= 10;
		prevNode = prevNode->prev;
	}
}
void print(Node* tail)
{
	if (tail == NULL) // Using tail recursion
		return;
	print(tail->prev);
	cout
		<< tail->data; // Print linked list in reverse order
}
// Driver code
int main()
{
	int n = 20;
	Node tail(1); // Create a node and initialise it by 1
	rep(i, 2, n)
		Multiply(&tail, i); // Run a loop from 2 to n and
							// multiply with tail's i
	print(&tail); // Print the linked list
	cout << endl;
	return 0;
}

OUTPUT:

243290200817123640000

Explanation

In the above program in C++, we have used linked list and in the multiply function we are taking tail node pointer and size n to calculate the factorial and after that printing it back to the console.


Related Topics

Static keyword in C++ vs Java

Both in C++ and Java, the static keyword is employed for essentially the same function. But there are some variations. The static keyword's similarities and differences between C++ and Java...

3 minutes read.

How to Sort an Array in C++

What is Sorting? Sorting is a process of arranging elements in sequential order, either numerically or alphabetically. The sorting of a numerical array can be accomplished using a variety of algorithms,...

4 minutes read.

C++ Inline function

A C++ function that extends in line when called is known as an inline function. It reduces function call overhead by having the compiler use the function code rather than...

4 minutes read.

Initialization of Data Members

In this tutorial, we'll look at how to initialise static member variables in C++. Static members, such as functions or variables, can be added to C++ classes. After declaring the...

1 minute read.

What does Buffer Flush mean in C++

A buffer flush, to explain simple layman's terms, is nothing but the transfer of computer data which is being stored in a rentable temporary memory of your computer running either...

3 minutes read.

Splitting a string in C++

Any programming language must have the ability to work with string data. For programming needs, we sometimes need to separate string data. Many computer languages provide a split() method that...

4 minutes read.

abs() function in C++

In C++, the abs() function returns the absolute value of any integer number. Using this function a negative integer is multiplied by -1 and positive number or zero is returned...

4 minutes read.

Delete Operator in C++

Overview We can reserve allocation for a variable or an array at runtime in C++. Dynamic memory allocation is the term for this. After utilising a variable in C++, we must...

4 minutes read.

Types of polymorphism in C++

What is polymorphism in C++ ? Polymorphism literally translates to "multiple forms". This indicates that the same thing behaves differently depending on the context in programming. Polymorphism is a feature of C++...

6 minutes read.

Boost split in C++ library

Boost::split in C++ library Boost offers strong tools for adding mature, well-tested libraries to the C++ standard library. The boost: split function, which is a component of the Boost string algorithm...

2 minutes read.

C++ Object Class

C++ Object Class Overview: C++ is a high-level programming language and an object-oriented programming language. An object-oriented language always has some properties of classes and objects. In this article, we...

4 minutes read.

Array of Vectors in C++ STL

Prerequisites: C++ STL Arrays and C++ STL Vector. A group of items kept in consecutive memory region is known as an array. It is to group similar objects of the same...

4 minutes read.

Program to convert infix to postfix expression in C++

Parentheses are frequently employed in mathematical formulas to make their interpretation easier to understand. However, with computers, parenthesis in an expression might lengthen the time it takes to find a...

7 minutes read.

Decimal to Binary in C++

What is the meaning of Decimal Numbers? Decimal numbers range from 0 to 9, there are a total of ten digits between 0 and 9. Any number with more than two...

3 minutes read.

Initialize Vector in C++

Initialize Vector in C++  The following comparison operators are defined for vector and those are given below. ==, <, <=, !=, >,>=  This allows you to access the element of a vector using...

3 minutes read.

Object in C++

In this article, we will learn about Object in C++. In short, an object is a stateful entity with behaviour. Data is referred to as state, and functionality is referred to...

3 minutes read.

Assertions in C/C++

Assertions are the statements used to check presumptions which is made by the programmers. Example: Assertion is used to verify whether the malloc returned by the pointer is NULL or not. For...

4 minutes read.

Dynamic Constructor in C++

Dynamic constructors create dynamic memory by using a dynamic memory allocator new within the constructor. This allows us to initialize objects dynamically. The term dynamic constructor is used when memory...

2 minutes read.

C++ Pointer

Pointer is a derived data type that stores the address of a variable. A pointer is used for memory management and dynamic memory allocation. Pointer works on the address of data rather than...

2 minutes read.

C++ Program to find the product array puzzle

Write a C++ program to form a product array from arr[] where product[i] is the product of all the array elements except arr[i]. Example Input: arr[]  = {10, 3, 5, 6,...

6 minutes read.