- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ program to find first digit in factorial of a number
In this article, we will be discussing a program to find the first digit in the factorial of a given number.
The basic approach for this is to find the factorial of the number and then get its first digit. But since factorials can end up being too large, we would make a small tweak.
At every point we would check for any trailing zeroes and remove if any exists. Since trailing zeroes isn’t having any effect on the first digit; our result won’t change.
Example
#include <bits/stdc++.h> using namespace std; int calc_1digit(int n) { long long int fact = 1; for (int i = 2; i <= n; i++) { fact = fact * i; //removing trailing zeroes while (fact % 10 == 0) fact = fact / 10; } //finding the first digit while (fact >= 10) fact = fact / 10; return fact; } int main() { int n = 37; cout << "The first digit : " << calc_1digit(n) << endl; return 0; }
Output
The first digit : 1
Advertisements