×

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

Include Guards in C++

In C++ programming, we frequently utilize a class more than once, so it is necessary to create a header file and include it in the main program. Now, occasionally a...

3 minutes read.

C++ File Handling

File handling is a mechanism that manipulates the data stored in files. File handling store output data from the program to external file and read file data to the program. There...

3 minutes read.

Pointers in C++

Pointers are a powerful feature in the C++ programming language, allowing developers to directly manipulate memory addresses and create more efficient and dynamic programs. However, pointers can also source various...

3 minutes read.

Sliding Window Technique in C++

Sliding Window Technique or Window Sliding Technique is a computational technique that is mainly used to reduce the use of nested loop and replace it with a single loop. It...

4 minutes read.

DES in C++

The popularity of the Data Encryption Standard (DES) is slightly declining as a result of the discovery that DES is susceptible to very strong attacks. Since DES is a block cypher,...

3 minutes read.

C++ Bitset

Overview In C++, bitset represents a fixed-sequence of some bits values by either 0 and 1. Zero represents the value as false or unset, while 1 represents the value as true...

4 minutes read.

Star pattern in C++ using For Loops

Star patterns are one of the most extensively utilized patterns in any programming language since they help to increase logical thinking and flow control understanding.In the C++ programming language, you...

3 minutes read.

Pure Virtual Function in C++ With Example Program

What is a Virtual Function? A virtual function is created inside a class with the keyword virtual. A virtual function does not have any value to be returned. Once a virtual...

3 minutes read.

Virtual class in C++

Introduction to Virtual Base class Virtual base classes can be utilized in virtual inheritance as a mechanism for examining many "instances" of a certain class while searching through multiple inheritances in...

6 minutes read.

C++ Overloading

C++ Overloading is a condition when two or more members have the same name with different parameter type or a different number of parameter. C++ overloading is two types: Function...

1 minute read.

Loops in C++

A loop statement in most programming languages allows us to execute a statement or a collection of statements numerous times. Control structures of programming languages vary, allowing for more complex...

6 minutes read.

Decltype type Specifier in C++

The primary use of C++ decltype is to inspect the declaration type of an entity in an expression. The auto keyword can declare a particular type of variable, whereas the...

4 minutes read.

Diamond Pattern in C++ using For Loop

For Loop: A for loop is a repetitive control structure that allows you to create a loop for executing a specific number of times. The syntax of for loop: In C++, a for...

5 minutes read.

C++ Queue

C++ queue: Queue in C++ is also a container adapter with the functionality of a queue. Queue is just the opposite of the stack in C++ because stack works on...

4 minutes read.

Substring in C++

A substring is a function in c++ that is imported from the string library. An element of a string is called a substring. A substring contains two parameters length and...

2 minutes read.

How to find the length of the vector in C++

Like dynamic arrays, vectors can automatically adjust their size when an element is added or removed, and the container manages its storage. Because vector items are stored in contiguous storage, iterators...

3 minutes read.

C++ String Concatenation

C++ String Concatenation In this section, we will learn about C ++ String Concatenation, what it does, how it works, and will also see its programs. What is the String Concatenation? The + operator...

3 minutes read.

Hierarchical Inheritance

C++ Hierarchical Inheritance Hierarchical inheritance inherits the property of one base class in more than one derived class.   C++ Hierarchical Inheritance Example #include <iostream>   using namespace std;   class Person {       char gender[10];       int age;   public:       void getPerson()       {           cout << "Age: "; cin >> age;           cout << "Gender: "; cin >> gender;       }       void dispPerson()       {           cout << "Age: " << age << endl;           cout << "Gender: " << gender << endl;       }   };   class Employee : public Person {       float salary;   public:       void getEmployee()       {           Person::getPerson();           cout << "Salary: Rs."; cin >> salary;       }       void dispEmployee()       {           Person::dispPerson();           cout << "Salary: Rs." << salary << endl;       }   };   class Student : public Person {       char level[20];   public:       void getStudent()       {           Person::getPerson();           cout << "Class: "; cin >> level;       }       void dispStudent()       {           Person::dispPerson();           cout << "Level: " << level << endl;       }   };   int main()   {       Person per;       Employee emp;       Student stu;       cout << "Student data" << endl;       cout << "Enter data" << endl;       stu.getStudent();       cout << endl << "Displaying data" << endl;       stu.dispPerson();       cout << endl << "Staff Data" << endl;       cout << "Enter data" << endl;       emp.getEmployee();       cout << endl << "Displaying data" << endl;       emp.dispPerson();   } Output: Student data Enter data Age: 10 Gender: f Class: 5 Displaying data Age: 10 Gender: f Employee data Enter data Age:...

1 minute read.

C++ Algorithms

There are plenty of programming paradigms that are closely associated with the implementations of code and simulate them into a proper functional one. This is done with the help of...

5 minutes read.

How to create a directory or folder in C/C++?

A directory is to lists all files and subdirectories in a directory, set of the files will be kept in the directory, which is a location. A subdirectory is a...

5 minutes read.