The Wayback Machine - https://web.archive.org/web/20240930170809/https://www.geeksforgeeks.org/last-non-zero-digit-factorial/
Open In App

Last non-zero digit of a factorial

Last Updated : 29 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a number n, find the last non-zero digit in n!.
Examples: 
 

Input  : n = 5
Output : 2
5! = 5 * 4 * 3 * 2 * 1 = 120
Last non-zero digit in 120 is 2.

Input  : n = 33
Output : 8

 

A Simple Solution is to first find n!, then find the last non-zero digit of n. This solution doesn’t work for even slightly large numbers due to arithmetic overflow.
A Better Solution is based on the below recursive formula 

Let D(n) be the last non-zero digit in n!
If tens digit (or second last digit) of n is odd
    D(n) = 4 * D(floor(n/5)) * D(Unit digit of n) 
If tens digit (or second last digit) of n is even
    D(n) = 6 * D(floor(n/5)) * D(Unit digit of n)

Illustration of the formula: 
For the numbers less than 10 we can easily find the last non-zero digit by the above simple solution, i.e., first computing n!, then finding the last digit. 
D(1) = 1, D(2) = 2, D(3) = 6, D(4) = 4, D(5) = 2, 
D(6) = 2, D(7) = 4, D(8) = 2, D(9) = 8.
 

D(1) to D(9) are assumed to be precomputed.

Example 1: n = 27 [Second last digit is even]:
D(27) = 6 * D(floor(27/5)) * D(7)
      = 6 * D(5) * D(7)
      = 6 * 2 * 4 
      = 48
Last non-zero digit is  8

Example 2: n = 33 [Second last digit is odd]:
D(33) = 4 * D(floor(33/5)) * D(3)
      = 4 * D(6) * 6
      = 4 * 2 * 6
      = 48
Last non-zero digit is 8

How does the above formula work? 
The below explanation provides intuition behind the formula. Readers may Refer http://math.stackexchange.com/questions/130352/last-non-zero-digit-of-a-factorial for complete proof.
 

14! = 14 * 13 * 12 * 11 * 10 * 9 * 8 * 7 * 
                     6 * 5 * 4 * 3 * 2 * 1

Since we are asked about last non-zero digit, 
we remove all 5's and equal number of 2's from
factors of 14!.  We get following:

14! = 14 * 13 * 12 * 11 * 2 * 9 * 8 * 7 *
                           6 * 3 * 2 * 1

Now we can get last non-zero digit by multiplying
last digits of above factors!

In n! a number of 2’s are always more than a number of 5’s. To remove trailing 0’s, we remove 5’s and equal number of 2’s. 
Let a = floor(n/5), b = n % 5. After removing an equal number of 5’s and 2’s, we can reduce the problem from n! to 2a * a! * b! 
D(n) = 2a * D(a) * D(b)
Implementation: 
 

C++




// C++ program to find last non-zero digit in n!
#include<bits/stdc++.h>
using namespace std;
 
// Initialize values of last non-zero digit of
// numbers from 0 to 9
int dig[] = {1, 1, 2, 6, 4, 2, 2, 4, 2, 8};
 
int lastNon0Digit(int n)
{
     if (n < 10)
        return dig[n];
 
    // Check whether tens (or second last) digit
    // is odd or even
    // If n = 375, So n/10 = 37 and (n/10)%10 = 7
    // Applying formula for even and odd cases.
    if (((n/10)%10)%2 == 0)
        return (6*lastNon0Digit(n/5)*dig[n%10]) % 10;
    else
        return (4*lastNon0Digit(n/5)*dig[n%10]) % 10;
}
 
// Driver code
int main()
{
    int n = 14;
    cout << lastNon0Digit(n);
    return 0;
}


C




// C program to find last non-zero digit in n!
#include<stdio.h>
 
// Initialize values of last non-zero digit of
// numbers from 0 to 9
int dig[] = {1, 1, 2, 6, 4, 2, 2, 4, 2, 8};
  
int lastNon0Digit(int n)
{
     if (n < 10)
        return dig[n];
  
      // Check whether tens (or second last) digit
    // is odd or even
    // If n = 375, So n/10 = 37 and (n/10)%10 = 7
    // Applying formula for even and odd cases.
    if (((n/10) % 10) % 2 == 0)
        return (6*lastNon0Digit(n/5)*dig[n%10]) % 10;
    else
        return (4*lastNon0Digit(n/5)*dig[n%10]) % 10;
}
  
// Driver code
int main()
{
    int n = 14;
    printf("%d",lastNon0Digit(n));
    return 0;
}
 
// This code is contributed by allwink45.


Java




// Java program to find last
// non-zero digit in n!
 
class GFG
{
    // Initialize values of last non-zero digit of
    // numbers from 0 to 9
    static int dig[] = {1, 1, 2, 6, 4, 2, 2, 4, 2, 8};
     
    static int lastNon0Digit(int n)
    {
        if (n < 10)
            return dig[n];
     
        // Check whether tens (or second last)
        // digit is odd or even
        // If n = 375, So n/10 = 37 and
        // (n/10)%10 = 7 Applying formula for
        // even and odd cases.
        if (((n / 10) % 10) % 2 == 0)
            return (6 * lastNon0Digit(n / 5)
                    * dig[n % 10]) % 10;
        else
            return (4 * lastNon0Digit(n / 5)
                    * dig[n % 10]) % 10;
    }
     
    // Driver code
    public static void main (String[] args)
    {
        int n = 14;
        System.out.print(lastNon0Digit(n));
    }
}
// This code is contributed by Anant Agarwal.


Python3




# Python program to find
# last non-zero digit in n!
 
# Initialize values of
# last non-zero digit of
# numbers from 0 to 9
dig= [1, 1, 2, 6, 4, 2, 2, 4, 2, 8]
  
def lastNon0Digit(n):
    if (n < 10):
        return dig[n]
  
     # Check whether tens (or second last) digit
     # is odd or even
     # If n = 375, So n/10 = 37 and (n/10)%10 = 7
     # Applying formula for even and odd cases.
    if (((n//10)%10)%2 == 0):
        return (6*lastNon0Digit(n//5)*dig[n%10]) % 10
    else:
        return (4*lastNon0Digit(n//5)*dig[n%10]) % 10
    return 0
 
# driver code
n = 14
 
print(lastNon0Digit(n))
 
# This code is contributed
# by Anant Agarwal.


C#




// C# program to find last
// non-zero digit in n!
using System;
 
class GFG {
     
    // Initialize values of last non-zero
    // digit of numbers from 0 to 9
    static int []dig = {1, 1, 2, 6, 4, 2, 2, 4, 2, 8};
     
    static int lastNon0Digit(int n)
    {
        if (n < 10)
            return dig[n];
     
        // Check whether tens (or second
        // last) digit is odd or even
        // If n = 375, So n/10 = 37 and
        // (n/10)%10 = 7 Applying formula
        // for even and odd cases.
        if (((n / 10) % 10) % 2 == 0)
            return (6 * lastNon0Digit(n / 5) *
                    dig[n % 10]) % 10;
        else
            return (4 * lastNon0Digit(n / 5) *
                    dig[n % 10]) % 10;
    }
     
    // Driver code
    public static void Main ()
    {
        int n = 14;
        Console.Write(lastNon0Digit(n));
    }
}
 
// This code is contributed by Nitin Mittal.


PHP




<?php
// PHP program to find last
// non-zero digit in n!
 
// Initialize values of
// last non-zero digit of
// numbers from 0 to 9
$dig = array(1, 1, 2, 6, 4,
             2, 2, 4, 2, 8);
 
function lastNon0Digit($n)
{
     
    global $dig;
    if ($n < 10)
        return $dig[$n];
 
    // Check whether tens(or second 
    // last) digit is odd or even
    // If n = 375, So n/10 = 37 and
    // (n/10)%10 = 7
    // Applying formula for even
    // and odd cases.
    if ((($n / 10) % 10) % 2 == 0)
        return (6 * lastNon0Digit($n / 5) *
                       $dig[$n % 10]) % 10;
    else
        return (4 * lastNon0Digit($n / 5) *
                        $dig[$n % 10]) % 10;
}
 
// Driver code
$n = 14;
echo(lastNon0Digit($n));
 
// This code is contributed by Ajit.
?>


Javascript




<script>
 
    // Javascript program to find
    // last non-zero digit in n!
     
    // Initialize values of last non-zero
    // digit of numbers from 0 to 9
    let dig = [1, 1, 2, 6, 4, 2, 2, 4, 2, 8];
       
    function lastNon0Digit(n)
    {
        if (n < 10)
            return dig[n];
       
        // Check whether tens (or second
        // last) digit is odd or even
        // If n = 375, So n/10 = 37 and
        // (n/10)%10 = 7 Applying formula
        // for even and odd cases.
        if ((parseInt(n / 10, 10) % 10) % 2 == 0)
         return (6 * lastNon0Digit(parseInt(n / 5, 10))
            * dig[n % 10]) % 10;
        else
         return (4 * lastNon0Digit(parseInt(n / 5, 10))
            * dig[n % 10]) % 10;
    }
     
    let n = 14;
      document.write(lastNon0Digit(n));
     
</script>


Output

2

Time complexity: O(log n)

Space complexity: O(log n)

 A Simple Solution based on recursion having worst-case Time Complexity O(nLog(n)).

Approach:-

  1. It is given that you have to find the last positive digit. Now a digit is made multiple of 10 if there are 2 and 5. They produce a number with last digit 0.
  2. Now what we can do is divide each array element into its shortest divisible form by 5 and increase count of such occurrences.
  3. Now divide each array element into its shortest divisible form by 2 and decrease count of such occurrences. This way we are not considering the multiplication of 2 and a 5 in our multiplication(number of 2’s present in multiplication result upto n is always more than number of 5’s).
  4. Multiply each number(after removing pairs of 2’s and 5’s) now and store just last digit by taking remainder by 10.
  5. Now call recursively for smaller numbers by (currentNumber – 1) as parameter.

Below is the implementation of the above approach: 

C++




#include <bits/stdc++.h>
using namespace std;
 
// Helper Function to return the rightmost non-zero digit
void callMeFactorialLastDigit(int n, int result[], int sumOf5)
{
  int number = n; // assigning to new variable.
  if (number == 1)
    return; // base case
 
  // To store the count of times 5 can
  // divide the number.
  while (number % 5 == 0) {
    number /= 5;
 
    // increase count of 5
    sumOf5++;
  }
 
  // Divide the number by
  // 2 as much as possible
  while (sumOf5 != 0 && (number & 1) == 0) {
    number >>= 1; // dividing the number by 2
    sumOf5--;
  }
 
  /*multiplied result and current number(after
    removing pairs) and do modular division to get the
    last digit of the resultant number.*/
  result[0] = (result[0] * (number % 10)) % 10;
 
  // calling again for (currentNumber - 1)
  callMeFactorialLastDigit(n - 1, result, sumOf5);
}
 
int lastNon0Digit(int n)
{
  int result[] = { 1 }; // single element array.
  callMeFactorialLastDigit(n, result, 0);
  return result[0];
}
 
int main()
{
  cout << lastNon0Digit(7) << endl;
  cout << lastNon0Digit(12) << endl;
  return 0;
}
 
// This code is contributed by rameshtravel07.


C




#include <stdio.h>
 
// Helper Function to return the rightmost non-zero digit
void callMeFactorialLastDigit(int n, int result[], int sumOf5)
{
int number = n;  // assaigning to new variable.
if (number == 1)
    return; // base case
 
    // To store the count of times 5 can
  // divide the number.
while (number % 5 == 0) {
    number /= 5;
 
      // increase count of 5
    sumOf5++;
}
 
  // Divide the number by
  // 2 as much as possible
while (sumOf5 != 0 && (number & 1) == 0) {
    number >>= 1;
    sumOf5--;
}
 
    /*multiplied result and current number(after
    removing pairs) and do modular division to get the
    last digit of the resultant number.*/
result[0] = (result[0] * (number % 10)) % 10;
 
   // calling again for (currentNumber - 1)
callMeFactorialLastDigit(n - 1, result, sumOf5);
}
 
int lastNon0Digit(int n)
{
int result[] = { 1 }; // single element array
callMeFactorialLastDigit(n, result, 0);
return result[0];
}
 
int main()
{
printf("%d\n",lastNon0Digit(7));
printf("%d",lastNon0Digit(12));
return 0;
}


Java




/*package whatever //do not write package name here */
 
import java.io.*;
 
class GFG {
    // Helper Function to return the rightmost non-zero
    // digit
    public static void
    callMeFactorialLastDigit(int n, int[] result,
                             int sumOf5)
    {
        int number = n; // assaigning to new variable.
        if (number == 1)
            return; // base case
 
        // To store the count of times 5 can
        // divide the number.
        while (number % 5 == 0) {
            number /= 5;
            // increase count of 5
            sumOf5++;
        }
 
        // Divide the number by
        // 2 as much as possible
        while (sumOf5 != 0 && (number & 1) == 0) {
            number >>= 1; // dividing the number by 2
            sumOf5--;
        }
 
        /*multiplied result and current number(after
        removing pairs) and do modular division to get the
        last digit of the resultant number.*/
        result[0] = (result[0] * (number % 10)) % 10;
        // calling again for (currentNumber - 1)
        callMeFactorialLastDigit(n - 1, result, sumOf5);
    }
 
    public static int lastNon0Digit(int n)
    {
        int[] result = { 1 }; // single element array.
        callMeFactorialLastDigit(n, result, 0);
        return result[0];
    }
 
    public static void main(String[] args)
    {
        System.out.println(lastNon0Digit(7)); // 3040
        System.out.println(lastNon0Digit(12)); // 479001600
    }
}
//This code is contributed by KaaL-EL.


Python3




# Helper Function to return the rightmost non-zero digit
def callMeFactorialLastDigit(n, result, sumOf5):
    number = n # assaigning to new variable.
    if number == 1:
        return # base case
 
    # To store the count of times 5 can
    # divide the number.
    while (number % 5 == 0):
        number = int(number / 5)
        # increase count of 5
        sumOf5 += 1
 
    # Divide the number by
    # 2 as much as possible
    while (sumOf5 != 0 and (number & 1) == 0):
        number >>= 1 # dividing the number by 2
        sumOf5 -= 1
 
    """multiplied result and current number(after
    removing pairs) and do modular division to get the
    last digit of the resultant number."""
    result[0] = (result[0] * (number % 10)) % 10
    # calling again for (currentNumber - 1)
    callMeFactorialLastDigit(n - 1, result, sumOf5)
 
def lastNon0Digit(n):
    result = [ 1 ] # single element array.
    callMeFactorialLastDigit(n, result, 0)
    return result[0]
 
print(lastNon0Digit(7)) # 3040
print(lastNon0Digit(12)) # 479001600
 
# This code is contributed by suresh07.


C#




using System;
class GFG {
     
    // Helper Function to return the rightmost non-zero
    // digit
    static void
    callMeFactorialLastDigit(int n, int[] result,
                             int sumOf5)
    {
        int number = n; // assaigning to new variable.
        if (number == 1)
            return; // base case
  
        // To store the count of times 5 can
        // divide the number.
        while (number % 5 == 0) {
            number /= 5;
            // increase count of 5
            sumOf5++;
        }
  
        // Divide the number by
        // 2 as much as possible
        while (sumOf5 != 0 && (number & 1) == 0) {
            number >>= 1; // dividing the number by 2
            sumOf5--;
        }
  
        /*multiplied result and current number(after
        removing pairs) and do modular division to get the
        last digit of the resultant number.*/
        result[0] = (result[0] * (number % 10)) % 10;
       
        // calling again for (currentNumber - 1)
        callMeFactorialLastDigit(n - 1, result, sumOf5);
    }
  
    static int lastNon0Digit(int n)
    {
        int[] result = { 1 }; // single element array.
        callMeFactorialLastDigit(n, result, 0);
        return result[0];
    }
     
  static void Main() {
    Console.WriteLine(lastNon0Digit(7)); // 3040
    Console.WriteLine(lastNon0Digit(12)); // 479001600
  }
}
 
// This code is contributed by mukesh07.


Javascript




<script>
    // Helper Function to return the rightmost non-zero
    // digit
    function callMeFactorialLastDigit(n, result, sumOf5)
    {
        let number = n; // assaigning to new variable.
        if (number == 1)
            return; // base case
  
        // To store the count of times 5 can
        // divide the number.
        while (number % 5 == 0) {
            number /= 5;
            // increase count of 5
            sumOf5++;
        }
  
        // Divide the number by
        // 2 as much as possible
        while (sumOf5 != 0 && (number & 1) == 0) {
            number >>= 1; // dividing the number by 2
            sumOf5--;
        }
  
        /*multiplied result and current number(after
        removing pairs) and do modular division to get the
        last digit of the resultant number.*/
        result[0] = (result[0] * (number % 10)) % 10;
        // calling again for (currentNumber - 1)
        callMeFactorialLastDigit(n - 1, result, sumOf5);
    }
  
    function lastNon0Digit(n)
    {
        let result = [ 1 ]; // single element array.
        callMeFactorialLastDigit(n, result, 0);
        return result[0];
    }
     
    document.write(lastNon0Digit(7) + "</br>"); // 3040
      document.write(lastNon0Digit(12)); // 479001600
     
    // This code is contributed by divyeshrabadiya07
</script>


Output

4
6

Time complexity :- O(N)

Space complexity :- O(1)

we used single element array (int[] result = {1}) instead of integer as Java is Strictly Pass by Value!. It does not allow pass by reference for primitive data types. That’s why I used a single element array so that the recursive function can change the value of variable(result here). If we would have taken (int result = 1) then this variable remain unaffected.

 



Previous Article
Next Article

Similar Reads

Last digit of a number raised to last digit of N factorial
Given two number X and N, the task is to find the last digit of X raised to last digit of N factorial, i.e. [Tex]X^{\left ( N! \right )mod 10} [/Tex].Examples: Input: X = 5, N = 2 Output: 5 Explanation: Since, 2! mod 10 = 2 therefore 52 = 25 and the last digit of 25 is 5.Input: X = 10, N = 4 Output: 0 Explanation: Since, 4! mod 10 = 24 mod 10 = 4 t
15 min read
Find the last digit when factorial of A divides factorial of B
We are given two numbers A and B such that B >= A. We need to compute the last digit of this resulting F such that F = B!/A! where 1 = A, B <= 10^18 (A and B are very large).Examples: Input : A = 2, B = 4Output : 2Explanation : A! = 2 and B! = 24. F = 24/2 = 12 --> last digit = 2Input : 107 109Output : 2As we know, factorial function grows
10 min read
Find last digit in factorial
Given a number n, we need to find the last digit in factorial n. Input : n = 4Output : 44! = 4 * 3 * 2 * 1. = 24. Last digit of 24 is 4. Input : n = 5Output : 55! = 5*4 * 3 * 2 * 1. = 120. Last digit of 120 is 0. A Naive Solution is to first compute fact = n!, then return the last digit of the result by doing fact % 10. This solution is inefficient
7 min read
Count of integer whose factorial of digit sum contains every digit of original number
Given an array arr[] of length n which contains positive integers (0 â‰Ī arr[i] â‰Ī 109), the task is to count the number of elements present in the given array such that the factorial of their digit sum (we will do digit sum while its value is greater than 10) contains every digit present in the original integer. Examples: Input: arr[] = [653, 663, 24
14 min read
Right most non-zero digit in multiplication of array elements
Given an array arr[] of N non-negative integers. The task is to find the rightmost non-zero digit in the product of array elements.Examples: Input: arr[] = {3, 5, 6, 90909009} Output: 7Input: arr[] = {7, 42, 11, 64} Output: 6 Result of multiplication is 206976 So the rightmost digit is 6 Approach: The question is too simple if you know basic maths.
8 min read
Count numbers with exactly K non-zero digits and distinct odd digit sum
Given an Integer N, and a number K, the task is to find out the total numbers from 0 to N which have exactly K non zero digits and the sum of those digits should be odd and that sum should be distinct. The number N can be as large as 10^18.Examples: Input : N = 10, K = 1 Output : 5 The numbers which follow the conditions are -> 1, 3, 5, 7 and 9
14 min read
Find the greater number closest to N having at most one non-zero digit
Given an integer N, the task is to find the closest number to N which is greater than N and contains at most one non-zero digit. Examples: Input: N = 540Output: 600Explanation: Since the number 600 contains only one non-zero digit, it is the required output is 600. Input: N = 1000Output: 2000 Approach: The problem can be solved based on the followi
9 min read
Count of Numbers in Range where first digit is equal to last digit of the number
Given a range represented by two positive integers L and R. Find the count of numbers in the range where the first digit is equal to the last digit of the number. Examples: Input : L = 2, R = 60 Output : 13 Explanation : Required numbers are 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44 and 55 Input : L = 1, R = 1000 Output : 108 Prerequisites: Digit DPTh
15+ min read
Count numbers in a range with digit sum divisible by K having first and last digit different
Given a range in the form of L and R, and a value K, the task is to count the numbers between the range L to R such that the sum of the digit is divisible by K, and the first digit is not equal to the last digit of the number. Examples: Input: L = 1, R = 10, K = 2 Output: 0 Explanation: The input numbers whose sum of the digits are divisible by 2 (
15 min read
Find the remainder when First digit of a number is divided by its Last digit
Given a number N, find the remainder when the first digit of N is divided by its last digit.Examples: Input: N = 1234 Output: 1 First digit = 1 Last digit = 4 Remainder = 1 % 4 = 1 Input: N = 5223 Output: 2 First digit = 5 Last digit = 3 Remainder = 5 % 3 = 2 Approach: Find the first digit and the last digit of the number. Find then the remainder w
5 min read
Count of pairs (A, B) in range 1 to N such that last digit of A is equal to the first digit of B
Given a number N, the task is to find the number of pairs (A, B) in the range [1, N] such that the last digit of A is equal to the first digit of B, and the first digit of A is equal to the last digit of B.Examples: Input: N = 25 Output: 17 Explanation: The pairs are: (1, 1), (1, 11), (2, 2), (2, 22), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8),
5 min read
Arrange array elements such that last digit of an element is equal to first digit of the next element
Given an array arr[] of integers, the task is to arrange the array elements such that the last digit of an element is equal to first digit of the next element. Examples: Input: arr[] = {123, 321} Output: 123 321 Input: arr[] = {451, 378, 123, 1254} Output: 1254 451 123 378 Naive approach: Find all the permutations of the array elements and then pri
9 min read
Count of N-digit numbers having digit XOR as single digit
Given an integer N, the task is to find the total count of N-Digit numbers such that the Bitwise XOR of the digits of the numbers is a single digit. Examples: Input: N = 1Output: 9Explanation: 1, 2, 3, 4, 5, 6, 7, 8, 9 are the numbers. Input: N = 2Output: 66Explanation: There are 66 such 2-digit numbers whose Xor of digits is a single digit number.
14 min read
Count ways to generate N digit number such that its every digit divisible by previous digit
Given a number N, the task is to count the number of ways to create an N digit number from digits 1 to 9 such that every digit is divisible by its previous digit that is if the number is represented by an array of digits A then A[i + 1] % A[i] == 0. print the answer modulo 109 + 7. Examples: Input: N = 2Output: 23Explanation: For N = 2 possible ans
15+ min read
Remove all zero-rows and all zero-columns from a Matrix
Given a matrix arr[][] of size N * M, the task is to print the matrix after removing all rows and columns from the matrix which consists of 0s only. Examples: Input: arr[][] ={ { 1, 1, 0, 1 }, { 0, 0, 0, 0 }, { 1, 1, 0, 1}, { 0, 1, 0, 1 } } Output: 111 111 011 Explanation: Initially, the matrix is as follows: arr[][] = { { 1, 1, 0, 1 }, { 0, 0, 0,
15+ min read
Find the last two digits of Factorial of a given Number
Given an integer N, the task is to find the last two digits of factorial of a number. Examples: Input: N = 7 Output: 40 Explanation: 7! = 5040Input: N = 11 Output: 00 Approach#1We can observe that for N >= 10, the last two places of its factorial will contain 0's only. Hence N! % 100 for any N >= 10 will always be 0. So we just calculate the
15 min read
First digit in factorial of a number
Given a positive integer n, find the first digit in its factorial. Examples : Input : n = 5 Output : 1 Factorial of 5 is 120 and first digit is 1. Input : 1000 Output : 4 A simple solution is to compute factorial of number, then find first digit in it. The above solution causes overflow soon. A better solution is to use the fact that factorial cont
5 min read
Find the index which is the last to be reduced to zero after performing a given operation
Given an integer array arr[] of size N and an integer K, the task is to find the index which will be the last to be reduced to zero after performing a given operation. The operation is described as follows: Starting from arr[0] to arr[N - 1], update each element as arr[i] = arr[i] - K.If arr[i] < K then set arr[i] = 0 and no further operation wi
6 min read
Minimize rows to be made zero for last column sum to be at most any one column
Given an N * M matrix mat[][] consisting of non-negative integers. In one operation, select any row and change all elements to 0. The task is to find the minimum number of operations required such that the sum of elements in the Mth column is less than or equal to the sum of elements in jth column for at least one 'j' ( where 1 â‰Ī 'j' â‰Ī 'M'-1). Exam
15+ min read
Steps to reduce N to zero by subtracting its most significant digit at every step
Given a number [Tex]N [/Tex]. Reduce this number to zero by subtracting the number by it's most significant digit(Left most digit) at every step. The task is to count the number of steps it takes to be reduced to zero. Examples: Input: 14 Output: 6 Steps: 14 - 1 = 13 13 - 1 = 12 12 - 1 = 11 11 - 1 = 10 10 - 1 = 9 9 - 9 = 0 Input: 20 Output: 12 Numb
9 min read
Count of Numbers in Range where the number does not contain more than K non zero digits
Given a range represented by two positive integers L and R and a positive integer K. Find the count of numbers in the range where the number does not contain more than K non zero digits.Examples: Input : L = 1, R = 1000, K = 3 Output : 1000 Explanation : All the numbers from 1 to 1000 are 3 digit numbers which obviously cannot contain more than 3 n
11 min read
Count numbers in range L-R that are divisible by all of its non-zero digits
Given a range l - r (inclusive), count the numbers that are divisible by all of its non-zero digits.Examples: Input : 1 9 Output : 9 Explanation: all the numbers are divisible by their digits in the range 1-9. Input : 10 20 Output : 5 Explanation: 10, 11, 12, 15, 20 Approach: 1. Run a loop to generate every number from l and r. 2. Check if every no
5 min read
Different ways to represent N as sum of K non-zero integers
Given N and K. The task is to find out how many different ways there are to represent N as the sum of K non-zero integers. Examples: Input: N = 5, K = 3 Output: 6 The possible combinations of integers are: ( 1, 1, 3 ) ( 1, 3, 1 ) ( 3, 1, 1 ) ( 1, 2, 2 ) ( 2, 2, 1 ) ( 2, 1, 2 ) Input: N = 10, K = 4 Output: 84 The approach to the problem is to observ
8 min read
Number of ways to reach the end of matrix with non-zero AND value
Given an N * N matrix arr[][] consisting of non-negative integers, the task is to find the number of ways to reach arr[N - 1][N - 1] with a non-zero AND value starting from the arr[0][0] by going down or right in every move. Whenever a cell arr[i][j] is reached, 'AND' value is updated as currentVal & arr[i][j]. Examples: Input: arr[][] = { {1,
7 min read
Smallest multiple of 3 which consists of three given non-zero digits
Given three non-zero digits 0 < A, B, C < 9. The task is to find the smallest number divisible by 3 all of whose digits are in set {A, B, C}. Note: It is not necessary to include all three digits. The result can be A, AA, AB, CCA etc.Examples: Input: A = 2, B = 4, C = 7 Output: 24 24 is the minimum number divisible by 3 that can be formed by
7 min read
Count of numbers between range having only non-zero digits whose sum of digits is N and number is divisible by M
Given a range [L, R] and two positive integers N and M. The task is to count the numbers in the range containing only non-zero digits whose sum of digits is equal to N and the number is divisible by M.Examples: Input: L = 1, R = 100, N = 8, M = 2 Output: 4 Only 8, 26, 44 and 62 are valid numbers Input: L = 1, R = 200, N = 4, M = 11 Output: 2 Only 2
14 min read
Smallest non-zero substring which has any permutation divisible by 2^K
Given a binary string S of length N and an integer K, the task is to find the smallest non-zero sub-string of S that can be jumbled to produce a binary string divisible by 2K. If no such sub-string exists then print -1. Note that K is always greater than 0.Examples: Input: S = "100", k = 1 Output: 2 Smallest substring that can be jumbled is "10". T
6 min read
Number of sub-sequences of non-zero length of a binary string divisible by 3
Given a binary string S of length N, the task is to find the number of sub-sequences of non-zero length which are divisible by 3. Leading zeros in the sub-sequences are allowed.Examples: Input: S = "1001" Output: 5 "11", "1001", "0", "0" and "00" are the only subsequences divisible by 3.Input: S = "1" Output: 0 Naive approach: Generate all the poss
5 min read
Find the numbers from 1 to N that contains exactly k non-zero digits
Prerequisites: Dynamic Programming, DigitDPGiven two integers N and K. The task is to find the number of integers between 1 and N (inclusive) that contains exactly K non-zero digits when written in base ten. Examples: Input: N = 100, K = 1 Output: 19 Explanation: The digits with exactly 1 non zero digits between 1 and 100 are: 1, 2, 3, 4, 5, 6, 7,
8 min read
Minimum steps to make sum and the product of all elements of array non-zero
Given an array arr of N integers, the task is to find the minimum steps in which the sum and product of all elements of the array can be made non-zero. In one step any element of the array can be incremented by 1.Examples: Input: N = 4, arr[] = {0, 1, 2, 3} Output: 1 Explanation: As product of all elements of the array is zero Increment the array e
7 min read