Open In App

Check if any permutation of a large number is divisible by 8

Last Updated : 05 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a large number N and the task is to check if any permutation of a large number is divisible by 8.

Examples: 

Input: N = 31462708
Output: Yes
Many of permutation of number N like 
34678120, 34278160 are divisible by 8. 

Input: 75
Output: No

A naive approach is to generate all permutations of the number N and check if(N % 8 == 0) and return true if any of the permutations is divisible by 8. 

An efficient approach is to use the fact that if the last three digits of a number are divisible by 8, then the number is also divisible by 8. Below are the required steps: 

  • Use a hash-table to count the occurrences of all digits in the given number.
  • Traverse for all three-digit numbers which are divisible by 8.
  • Check if the digits in the three-digit number are in the hash-table.
  • If yes a number can be formed by permutation where the last three digits combine to form the three-digit number.
  • If none of the three-digit numbers can be formed, return false.

Below is the implementation of the above approach: 

C++




// C++ program to check if any permutation of
// a large number is divisible by 8 or not
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if any permutation
// of a large number is divisible by 8
bool solve(string n, int l)
{
 
    // Less than three digit number
    // can be checked directly.
    if (l < 3) {
        if (stoi(n) % 8 == 0)
            return true;
 
        // check for the reverse of a number
        reverse(n.begin(), n.end());
        if (stoi(n) % 8 == 0)
            return true;
        return false;
    }
 
    // Stores the Frequency of characters in the n.
    int hash[10] = { 0 };
    for (int i = 0; i < l; i++)
        hash[n[i] - '0']++;
 
    // Iterates for all three digit numbers
    // divisible by 8
    for (int i = 104; i < 1000; i += 8) {
 
        int dup = i;
 
        // stores the frequency of all single
        // digit in three-digit number
        int freq[10] = { 0 };
        freq[dup % 10]++;
        dup = dup / 10;
        freq[dup % 10]++;
        dup = dup / 10;
        freq[dup % 10]++;
 
        dup = i;
 
        // check if the original number has
        // the digit
        if (freq[dup % 10] > hash[dup % 10])
            continue;
        dup = dup / 10;
 
        if (freq[dup % 10] > hash[dup % 10])
            continue;
        dup = dup / 10;
 
        if (freq[dup % 10] > hash[dup % 10])
            continue;
 
        return true;
    }
 
    // when all are checked its not possible
    return false;
}
 
// Driver Code
int main()
{
    string number = "31462708";
    int l = number.length();
 
    if (solve(number, l))
        cout << "Yes";
    else
        cout << "No";
    return 0;
}


Java




// Java program to check if
// any permutation of a large
// number is divisible by 8 or not
import java.util.*;
 
class GFG
{
    // Function to check if any
    // permutation of a large
    // number is divisible by 8
    public static boolean solve(String n, int l)
    {
         
        // Less than three digit number
        // can be checked directly.
        if (l < 3)
        {
            if (Integer.parseInt(n) % 8 == 0)
                return true;
     
            // check for the reverse
            // of a number
            n = new String((new StringBuilder()).append(n).reverse());
             
            if (Integer.parseInt(n) % 8 == 0)
                return true;
            return false;
        }
     
        // Stores the Frequency of
        // characters in the n.
        int []hash = new int[10];
        for (int i = 0; i < l; i++)
            hash[n.charAt(i) - '0']++;
     
        // Iterates for all
        // three digit numbers
        // divisible by 8
        for (int i = 104; i < 1000; i += 8)
        {
            int dup = i;
     
            // stores the frequency of
            // all single digit in
            // three-digit number
            int []freq = new int[10];
            freq[dup % 10]++;
            dup = dup / 10;
            freq[dup % 10]++;
            dup = dup / 10;
            freq[dup % 10]++;
     
            dup = i;
     
            // check if the original
            // number has the digit
            if (freq[dup % 10] >
                hash[dup % 10])
                continue;
            dup = dup / 10;
     
            if (freq[dup % 10] >
                hash[dup % 10])
                continue;
            dup = dup / 10;
     
            if (freq[dup % 10] >
                hash[dup % 10])
                continue;
     
            return true;
        }
     
        // when all are checked
        // its not possible
        return false;
    }
     
    // Driver Code
    public static void main(String[] args)
    {
        String number = "31462708";
         
        int l = number.length();
     
        if (solve(number, l))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
 
// This code is contributed
// by Harshit Saini


Python3




# Python3 program to check if
# any permutation of a large
# number is divisible by 8 or not
 
# Function to check if any
# permutation of a large
# number is divisible by 8
def solve(n, l):
     
    # Less than three digit
    # number can be checked
    # directly.
    if l < 3:
        if int(n) % 8 == 0:
            return True
         
        # check for the reverse
        # of a number
        n = n[::-1]
 
         
        if int(n) % 8 == 0:
            return True
        return False
 
    # Stores the Frequency of
    # characters in the n.
    hash = 10 * [0]
    for i in range(0, l):
        hash[int(n[i]) - 0] += 1;
 
    # Iterates for all
    # three digit numbers
    # divisible by 8
    for i in range(104, 1000, 8):
        dup = i
 
        # stores the frequency
        # of all single digit
        # in three-digit number
        freq = 10 * [0]
        freq[int(dup % 10)] += 1;
        dup = dup / 10
        freq[int(dup % 10)] += 1;
        dup = dup / 10
        freq[int(dup % 10)] += 1;
         
        dup = i
         
        # check if the original
        # number has the digit
        if (freq[int(dup % 10)] >
            hash[int(dup % 10)]):
            continue;
        dup = dup / 10;
         
        if (freq[int(dup % 10)] >
            hash[int(dup % 10)]):
            continue;
        dup = dup / 10
         
        if (freq[int(dup % 10)] >
            hash[int(dup % 10)]):
            continue;
         
        return True
 
    # when all are checked
    # its not possible
    return False
     
# Driver Code
if __name__ == "__main__":
     
    number = "31462708"
     
    l = len(number)
     
    if solve(number, l):
        print("Yes")
    else:
        print("No")
         
# This code is contributed
# by Harshit Saini


C#




// C# program to check if
// any permutation of a large
// number is divisible by 8 or not
using System;
using System.Collections.Generic;
     
class GFG
{
    // Function to check if any
    // permutation of a large
    // number is divisible by 8
    public static bool solve(String n, int l)
    {
         
        // Less than three digit number
        // can be checked directly.
        if (l < 3)
        {
            if (int.Parse(n) % 8 == 0)
                return true;
     
            // check for the reverse
            // of a number
            n = reverse(n);
             
            if (int.Parse(n) % 8 == 0)
                return true;
            return false;
        }
     
        // Stores the Frequency of
        // characters in the n.
        int []hash = new int[10];
        for (int i = 0; i < l; i++)
            hash[n[i] - '0']++;
     
        // Iterates for all
        // three digit numbers
        // divisible by 8
        for (int i = 104; i < 1000; i += 8)
        {
            int dup = i;
     
            // stores the frequency of
            // all single digit in
            // three-digit number
            int []freq = new int[10];
            freq[dup % 10]++;
            dup = dup / 10;
            freq[dup % 10]++;
            dup = dup / 10;
            freq[dup % 10]++;
     
            dup = i;
     
            // check if the original
            // number has the digit
            if (freq[dup % 10] >
                hash[dup % 10])
                continue;
            dup = dup / 10;
     
            if (freq[dup % 10] >
                hash[dup % 10])
                continue;
            dup = dup / 10;
     
            if (freq[dup % 10] >
                hash[dup % 10])
                continue;
     
            return true;
        }
     
        // when all are checked
        // its not possible
        return false;
    }
     
    static String reverse(String input)
    {
        char[] a = input.ToCharArray();
        int l, r = 0;
        r = a.Length - 1;
 
        for (l = 0; l < r; l++, r--)
        {
            // Swap values of l and r
            char temp = a[l];
            a[l] = a[r];
            a[r] = temp;
        }
        return String.Join("",a);
    }
     
    // Driver Code
    public static void Main(String[] args)
    {
        String number = "31462708";
         
        int l = number.Length;
     
        if (solve(number, l))
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
    }
}
 
// This code is contributed by Princi Singh


PHP




<?php
error_reporting(0);
// PHP program to check
// if any permutation of
// a large number is
// divisible by 8 or not
 
// Function to check if
// any permutation of a
// large number is divisible by 8
function solve($n, $l)
{
 
    // Less than three digit
    // number can be checked
    // directly.
    if ($l < 3)
    {
        if (intval($n) % 8 == 0)
            return true;
 
        // check for the
        // reverse of a number
        strrev($n);
        if (intval($n) % 8 == 0)
            return true;
        return false;
    }
 
    // Stores the Frequency of
    // characters in the n.
    $hash[10] = array(0);
    for ($i = 0; $i < $l; $i++)
        $hash[$n[$i] - '0']++;
 
    // Iterates for all three
    // digit numbers divisible by 8
    for ($i = 104;
         $i < 1000; $i += 8)
    {
 
        $dup = $i;
 
        // stores the frequency of
        // all single digit in
        // three-digit number
        $freq[10] = array(0);
        $freq[$dup % 10]++;
        $dup = $dup / 10;
        $freq[$dup % 10]++;
        $dup = $dup / 10;
        $freq[$dup % 10]++;
 
        $dup = $i;
 
        // check if the original
        // number has the digit
        if ($freq[$dup % 10] >
            $hash[$dup % 10])
            continue;
        $dup = $dup / 10;
 
        if ($freq[$dup % 10] >
            $hash[$dup % 10])
            continue;
        $dup = $dup / 10;
 
        if ($freq[$dup % 10] >
            $hash[$dup % 10])
            continue;
 
        return true;
    }
 
    // when all are checked
    // its not possible
    return false;
}
 
// Driver Code
$number = "31462708";
$l = strlen($number);
 
if (solve($number, $l))
    echo "Yes";
else
    echo "No";
 
// This code is contributed
// by Akanksha Rai(Abby_akku)


Javascript




<script>
 
      // JavaScript program to check if
      // any permutation of a large
      // number is divisible by 8 or not
       
      // Function to check if any
      // permutation of a large
      // number is divisible by 8
      function solve(n, l) {
        // Less than three digit number
        // can be checked directly.
        if (l < 3) {
          if (parseInt(n) % 8 === 0) return true;
 
          // check for the reverse
          // of a number
          n = reverse(n);
 
          if (parseInt(n) % 8 === 0) return true;
          return false;
        }
 
        // Stores the Frequency of
        // characters in the n.
        var hash = new Array(10).fill(0);
        for (var i = 0; i < l; i++) hash[parseInt(n[i]) - 0]++;
 
        // Iterates for all
        // three digit numbers
        // divisible by 8
        for (var i = 104; i < 1000; i += 8) {
          var dup = i;
 
          // stores the frequency of
          // all single digit in
          // three-digit number
          var freq = new Array(10).fill(0);
          freq[parseInt(dup % 10)]++;
          dup = dup / 10;
          freq[parseInt(dup % 10)]++;
          dup = dup / 10;
          freq[parseInt(dup % 10)]++;
 
          dup = i;
 
          // check if the original
          // number has the digit
          if (freq[parseInt(dup % 10)] > hash[parseInt(dup % 10)])
          continue;
          dup = dup / 10;
 
          if (freq[parseInt(dup % 10)] > hash[parseInt(dup % 10)])
          continue;
          dup = dup / 10;
 
          if (freq[parseInt(dup % 10)] > hash[parseInt(dup % 10)])
          continue;
 
          return true;
        }
 
        // when all are checked
        // its not possible
        return false;
      }
 
      function reverse(input) {
        var a = input.split("");
        var l,
          r = 0;
        r = a.length - 1;
 
        for (l = 0; l < r; l++, r--) {
          // Swap values of l and r
          var temp = a[l];
          a[l] = a[r];
          a[r] = temp;
        }
        return a.join("");
      }
 
      // Driver Code
      var number = "31462708";
 
      var l = number.length;
 
      if (solve(number, l))
      document.write("Yes");
      else
      document.write("No");
       
</script>


Output

Yes

Time Complexity: O(L), where L is the number of digits in the number.

Auxiliary space: O(1) as it is using constant space



Similar Reads

Check if any large number is divisible by 19 or not
Given a number, the task is to quickly check if the number is divisible by 19 or not. Examples: Input : x = 38Output : YesInput : x = 47Output : NoA solution to the problem is to extract the last digit and add 2 times of last digit to remaining number and repeat this process until a two digit number is obtained. If the obtained two digit number is
9 min read
Check if any large number is divisible by 17 or not
Given a number, the task is to quickly check if the number is divisible by 17 or not. Example: Input : x = 34Output : YesInput : x = 47Output : NoA solution to the problem is to extract the last digit and subtract 5 times of the last digit from the remaining number and repeat this process until a two-digit number is obtained. If the obtained two-di
10 min read
Check if any permutation of a number is divisible by 3 and is Palindromic
Given an integer N. The task is to check whether any of its permutations is a palindrome and divisible by 3 or not. Examples: Input : N = 34734 Output : TrueInput : N = 34234 Output : False Basic Approach: First, create all permutations of a given integer and for each permutation check whether the permutation is a palindrome and divisible by 3 as w
7 min read
Check if any permutation of a number without any leading zeros is a power of 2 or not
Given an integer N, the task is to check if any permutation of N without any leading zeros is a power of 2. If any such permutation of the given number exists, then print that permutation. Otherwise, print No. Examples: Input: N = 46Output: 64Explanation:The permutation of 46 which is perfect power of 2 is 64( = 26) Input: N = 75Output: NoExplanati
9 min read
Check if any permutation of array contains sum of every adjacent pair not divisible by 3
Given an array arr[] consisting of N integers, the task is to check if any permutation of the array elements exists where the sum of every pair of adjacent elements is not divisible by 3. If it is possible, then print “Yes”. Otherwise, print “No”. Examples: Input: arr[] = {1, 2, 3, 3}Output: YesExplanation:Since there exist at least 1 combination {
7 min read
Check if a large number is divisible by a number which is a power of 2
Given a large number in the form of a string str and a number K, the task is to check if the number formed by string str is divisible by the K or not, where K is a power of 2. Examples: Input: str = "5426987513245621541524288", num = 64 Output: Yes Explanation: Since log2(64) = 6, so the number formed by the last 6 digits from the string str is div
7 min read
Check if any permutation of N equals any power of K
Given a positive integer N and K where [Tex]2 \leq N \leq 10^{18} [/Tex] and [Tex]2 \leq K \leq N [/Tex] . The task is to check whether any permutation of digits of N equals any power of K. If possible return "True" otherwise return "False".Examples: Input: N = 96889010407, K = 7 Output: True Explanation: 96889010407 = 713 Input : N = 123456789, K
6 min read
Find permutation of n which is divisible by 3 but not divisible by 6
Given an integer [Tex]n [/Tex]. The task is to find another integer which is permutation of n, divisible by 3 but not divisible by 6. Given that n is divisible by 6. If no such permutation is possible print -1. Examples: Input: n = 336 Output: 363 Input: n = 48 Output: -1 For a number to be divisible by 6, it must be divisible by 3 as well as 2, me
5 min read
Number of factors of very large number N modulo M where M is any prime number
Given a large number N, the task is to find the total number of factors of the number N modulo M where M is any prime number. Examples: Input: N = 9699690, M = 17 Output: 1 Explanation: Total Number of factors of 9699690 is 256 and (256 % 17) = 1Input: N = 193748576239475639, M = 9 Output: 8 Explanation: Total Number of factors of 9699690 is 256 an
8 min read
Given a large number, check if a subsequence of digits is divisible by 8
Given a number of at most 100 digits. We have to check if it is possible, after removing certain digits, to obtain a number of at least one digit which is divisible by 8. We are forbidden to rearrange the digits. Examples : Input : 1787075866 Output : Yes There exist more one or more subsequences divisible by 8. Example subsequences are 176, 16 and
25 min read