Find the last digit when factorial of A divides factorial of B in C++

C++Server Side ProgrammingProgramming

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

 Live Demo

#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
raja
Published on 19-Dec-2019 11:36:44
Advertisements