- 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
Find the last digit when factorial of A divides factorial of B in C++
If we have two integers A and B, and B >= A, we have to compute the last digit of the B! / A! When the value of A = 2 and B = 4, then result is 2, 2! = 2 and 4! = 24, so 24/2 = 12. the last digit is 2.
As we know that the last digit of factorial will be in set {0, 1, 2, 4, 6}, then follow these steps to solve this problem −
- We will find the difference between A and B
- if diff >=5, then answer is 0
- otherwise, iterate from (A + 1) to B. Then multiply and store them.
- The last digit of multiplication will be the answer.
Example
#include<iostream> using namespace std; int findLastDigit(long long int A, long long int B) { int x = 1; if (A == B) return 1; else if ((B - A) >= 5) return 0; else { for (long long int i = A + 1; i <= B; i++) x = (x * (i % 10)) % 10; return x % 10; } } int main() { cout << "Last digit is: " << findLastDigit(2, 4); }
Output
Last digit is: 2
Advertisements