The Wayback Machine - https://web.archive.org/web/20240917121421/https://www.geeksforgeeks.org/check-divisibility-large-number-999/
Open In App

To check divisibility of any large number by 999

Last Updated : 15 Sep, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Show Topics
Solve Problem
Easy
40.56%
3.1K

You are given an n-digit large number, you have to check whether it is divisible by 999 without dividing or finding modulo of number by 999.

Examples: 

Input : 235764 
Output : Yes

Input : 23576 
Output : No

Since input number may be very large, we cannot use n % 999 to check if a number is divisible by 999 or not, especially in languages like C/C++. The idea is based on following fact.

Recommended Practice

The solutions is based on below fact.

A number is divisible by 999 if sum of its 3-digit-groups (if required groups are formed by appending a 0s at the beginning) is divisible by 999.

Illustration: 

Input : 235764 
Output : Yes
Explanation : Step I - read input : 235, 764
              Step II - 235 + 764 = 999
              As result is 999 then we can 
              conclude that it is divisible by 999.

Input : 1244633121
Output : Yes
Explanation : Step I - read input : 1, 244, 633, 121
              Step II - 001 + 244 + 633 + 121 = 999
              As result is 999 then we can conclude 
              that it is divisible by 999.

Input : 999999999
Output : Yes
Explanation : Step I - read input : 999, 999, 999
              Step II - 999 + 999 + 999 = 2997
              Step III - 997 + 002 = 999
              As result is 999 then we can conclude  
              that it is divisible by 999.

How does this work? 

Let us consider 235764, we can write it as
235764 = 2*105 + 3*104 + 5*103 + 
         7*102 + 6*10 + 4

The idea is based on below observation:
Remainder of 103 divided by 999 is 1
For i > 3, 10i % 999 = 10i-3 % 999 

Let us see how we use above fact.
Remainder of 2*105 + 3*104 + 5*103 + 
7*102 + 6*10 + 4
Remainder with 999 can be written as : 
2*100 + 3*10 + 5*1 + 7*100 + 6*10 + 4 
The above expression is basically sum of
groups of size 3.

Since the sum is divisible by 999, answer is yes.

A simple and efficient method is to take input in form of string (make its length in form of 3*m by adding 0 to left of number if required) and then you have to add the digits in blocks of three from right to left until it become a 3 digit number and if that result is 999 we can say that number is divisible by 999.

As in the case of “divisibility by 9” we check that sum of all digit is divisible by 9 or not, the same thing follows within the case of divisibility by 999. We sum up all 3-digits group from right to left and check whether the final result is 999 or not.

Implementation:
 

C++




// CPP for divisibility of number by 999
#include<bits/stdc++.h>
using namespace std;
  
// function to check divisibility
bool isDivisible999(string num)
{
    int n = num.length();
    if (n == 0 && num[0] == '0')
       return true;
  
    // Append required 0s at the beginning.
    if (n % 3 == 1)
       num = "00" + num;
    if (n % 3 == 2)
       num = "0" + num;
  
    // add digits in group of three in gSum
    int gSum = 0;
    for (int i = 0; i<n; i++)
    {
        // group saves 3-digit group
        int group = 0;
        group += (num[i++] - '0') * 100;
        group += (num[i++] - '0') * 10;
        group += num[i] - '0';
        gSum += group;
    }
  
    // calculate result till 3 digit sum
    if (gSum > 1000)
    {
        num = to_string(gSum);
        n = num.length();
        gSum = isDivisible999(num);
    }
    return (gSum == 999);
}
  
// driver program
int main()
{
    string num = "1998";
    int n = num.length();
    if (isDivisible999(num))
        cout << "Divisible";
    else
        cout << "Not divisible";
    return 0;
}


Java




//Java for divisibility of number by 999
  
class Test
{    
    // Method to check divisibility
    static boolean isDivisible999(String num)
    {
        int n = num.length();
        if (n == 0 && num.charAt(0) == '0')
           return true;
       
        // Append required 0s at the beginning.
        if (n % 3 == 1)
           num = "00" + num;
        if (n % 3 == 2)
           num = "0" + num;
       
        // add digits in group of three in gSum
        int gSum = 0;
        for (int i = 0; i<n; i++)
        {
            // group saves 3-digit group
            int group = 0;
            group += (num.charAt(i++) - '0') * 100;
            group += (num.charAt(i++) - '0') * 10;
            group += num.charAt(i) - '0';
            gSum += group;
        }
       
        // calculate result till 3 digit sum
        if (gSum > 1000)
        {
            num = Integer.toString(gSum);
            n = num.length();
            gSum = isDivisible999(num) ? 1 : 0;
        }
        return (gSum == 999);
    }
      
    // Driver method
    public static void main(String args[]) 
    {
        String num = "1998";
       
        System.out.println(isDivisible999(num) ? "Divisible" : "Not divisible");
    }
}


Python 3




# Python3 program for divisibility 
# of number by 999 
  
# function to check divisibility 
def isDivisible999(num):
    n = len(num);
    if(n == 0 or num[0] == '0'):
        return true
  
    # Append required 0s at the beginning.
    if((n % 3) == 1):
        num = "00" + num
    if((n % 3) == 2):
        num = "0" + num
  
    # add digits in group of three in gSum     
    gSum = 0
    for i in range(0, n, 3):
          
        # group saves 3-digit group 
        group = 0
        group += (ord(num[i]) - 48) * 100
        group += (ord(num[i + 1]) - 48) * 10
        group += (ord(num[i + 2]) - 48)
        gSum += group
  
    # calculate result till 3 digit sum     
    if(gSum > 1000):
        num = str(gSum)
        n = len(num)
        gSum = isDivisible999(num)
    return (gSum == 999) 
  
# Driver code 
if __name__=="__main__":
    num = "1998"
    n = len(num)
    if(isDivisible999(num)):
        print("Divisible")
    else:
        print("Not divisible")
          
# This code is contributed
# by Sairahul Jella


C#




// C# code for divisibility of number by 999 
  
using System;
class Test 
{ 
    // Method to check divisibility 
    static bool isDivisible999(String num) 
    { 
        int n = num.Length; 
        if (n == 0 && num[0] == '0') 
        return true; 
      
        // Append required 0s at the beginning. 
        if (n % 3 == 1) 
        num = "00" + num; 
        if (n % 3 == 2) 
        num = "0" + num; 
      
        // add digits in group of three in gSum 
        int gSum = 0; 
        for (int i = 0; i<n; i++) 
        { 
            // group saves 3-digit group 
            int group = 0; 
            group += (num[i++] - '0') * 100; 
            group += (num[i++] - '0') * 10; 
            group += num[i] - '0'; 
            gSum += group; 
        } 
      
        // calculate result till 3 digit sum 
        if (gSum > 1000) 
        { 
            num = Convert.ToString(gSum); 
            n = num.Length ; 
            gSum = isDivisible999(num) ? 1 : 0; 
        } 
        return (gSum == 999); 
    } 
      
    // Driver method 
    public static void Main() 
    { 
        String num = "1998"; 
      
        Console.WriteLine(isDivisible999(num) ? "Divisible" : "Not divisible"); 
    } 
    // This code is contributed by Ryuga
} 


PHP




<?php
// PHP for divisibility of number by 999
  
// function to check divisibility
function isDivisible999($num)
{
    $n = strlen($num);
    if ($n == 0 && $num[0] == '0')
    return true;
  
    // Append required 0s at the beginning.
    if ($n % 3 == 1)
        $num = "00" . $num;
    if ($n % 3 == 2)
        $num = "0" . $num;
  
    // add digits in group of three in gSum
    $gSum = 0;
    for ($i = 0; $i < $n; $i += 3)
    {
        // group saves 3-digit group
        $group = 0;
        $group += (ord($num[$i]) - 48) * 100;
        $group += (ord($num[$i + 1]) - 48) * 10;
        $group += (ord($num[$i + 2]) - 48);
        $gSum += $group;
    }
      
    // calculate result till 3 digit sum
    if ($gSum > 1000)
    {
        $num = strval($gSum);
        $n = strlen($num);
        $gSum = isDivisible999($num);
    }
    return ($gSum == 999);
}
  
// Driver Code
$num = "1998";
if (isDivisible999($num))
    echo "Divisible";
else
    echo "Not divisible";
  
// This code is contributed by mits
?>


Javascript




<script>
// Javascript for divisibility of number by 999
  
// function to check divisibility
function isDivisible999(num)
{
    let n = num.length;
    if (n == 0 && num[0] == '0')
    return true;
  
    // Append required 0s at the beginning.
    if (n % 3 == 1)
        num = "00" + num;
    if (n % 3 == 2)
        num = "0" + num;
  
    // add digits in group of three in gSum
    let gSum = 0;
    for (let i = 0; i < n; i += 3)
    {
        // group saves 3-digit group
        group = 0;
        group += (num.charCodeAt(i) - 48) * 100;
        group += (num.charCodeAt(i + 1) - 48) * 10;
        group += (num.charCodeAt(i + 2) - 48);
        gSum += group;
    }
      
    // calculate result till 3 digit sum
    if (gSum > 1000)
    {
        num = String(gSum);
        n = strlen(num);
        gSum = isDivisible999(num);
    }
    return (gSum == 999);
}
  
// Driver Code
let num = "1998";
if (isDivisible999(num))
    document.write("Divisible");
else
    document.write("Not divisible");
  
// This code is contributed by _saurabh_jaiswal.
</script>


Output

Divisible

Time complexity : O(n) 
Auxiliary Space : O(1)

Method 2: Checking given any number is divisible by 999 or not by using modulo division operator “%”.  

Implementation:

C++




#include <iostream>
using namespace std;
int main()
{
    //input
    long long int n=235764;
       
       
    // finding given number is divisible by 999 or not
    if (n%999==0)
    {
        cout << "Yes";
    }
    else
    {
        cout << "No";
    }
     
    return 0;
}
  
// This code is contributed by satwik4409.


Java




/*package whatever //do not write package name here */
import java.io.*;
  
class GFG {
  public static void main (String[] args) {
  
    // input 
    long n = 235764;
  
    // finding given number is divisible by 999 or not
    if (n % 999 == 0)
      System.out.println("Yes");
    else
      System.out.println("No"); 
  
  }
}
  
// This code is contributed by ksrikanth0498.


Python3




# Python code 
# To check whether the given number is divisible by 999 or not
  
#input 
n=235764
# the above input can also be given as n=input() -> taking input from user
# finding given number is divisible by 999 or not
if int(n)%999==0:
  print("Yes") 
else: 
  print("No") 
    
  # this code is contributed by gangarajula laxmi


C#




// C# code 
// To check whether the given number is divisible by 999 or not
using System;
  
public class GFG{
  
    static public void Main ()
    {
        
       // input 
       long n = 235764;
        
        // finding given number is divisible by 999 or not
       if (n % 999 == 0)
            Console.Write("Yes");
        else
            Console.Write("No"); 
    } 
}
  
// This code is contributed by ksrikanth0498


PHP




<?php
    $num =235764;
    // checking if the given number is divisible by 999 or
    // not using modulo division operator if the output of
    // num%999 is equal to 0 then given number is divisible
    // by 999 otherwise not divisible by 999
    if ($num % 999 == 0) {
        echo "Yes";
    }
    else {
        echo "No";
    }
    
?>


Javascript




<script>
        // JavaScript code for the above approach
        //input 
        let n = 235764
          
        // finding given number is divisible by 999 or not
        if (n % 999 == 0)
            document.write("Yes")
        else
            document.write("No")
    // This code is contributed by Potta Lokesh
    </script>


Output

Yes

Time Complexity : O(1)

Auxiliary Space: O(1)

Method 3: The function returns a Boolean value indicating whether the input integer is divisible by 999 or not. The function calculates this by checking if the sum of the digits of num is divisible by 9 and if the last three digits of num are divisible by 27. This code then tests the function with the examples: 999, 998 and 9987 and outputs the values True, False and False respectively.

C++




convert C++ code into Javascript code
  
#include <bits/stdc++.h>
using namespace std;
  
bool is_divisible_by_999(int num) {
    string num_str = to_string(num);
    int sum = 0;
    for (char digit : num_str) {
        sum += digit - '0';
    }
    return sum % 9 == 0 && stoi(num_str.substr(num_str.length() - 3)) % 27 == 0;
}
  
int main() {
    cout << is_divisible_by_999(999) << endl;  // True
    cout << is_divisible_by_999(998) << endl;  // False
    cout << is_divisible_by_999(9987) << endl;  // False
    return 0;
}


Java




public class Main {
    public static boolean isDivisibleBy999(int num) {
        String numStr = String.valueOf(num);
        int sum = 0;
        for (int i = 0; i < numStr.length(); i++) {
            char digit = numStr.charAt(i);
            sum += Character.getNumericValue(digit);
        }
        return sum % 9 == 0 && Integer.parseInt(numStr.substring(numStr.length() - 3)) % 27 == 0;
    }
  
    public static void main(String[] args) {
        System.out.println(isDivisibleBy999(999));  // true
        System.out.println(isDivisibleBy999(998));  // false
        System.out.println(isDivisibleBy999(9987)); // false
    }
}


Python3




def is_divisible_by_999(num):
    num_str = str(num)
    return sum(int(digit) for digit in num_str) % 9 == 0 and int(num_str[-3:]) % 27 == 0
  
print(is_divisible_by_999(999)) # True
print(is_divisible_by_999(998)) # False
print(is_divisible_by_999(9987)) # False


C#




using System;
  
class Program {
    static bool IsDivisibleBy999(int num) {
        string numStr = num.ToString();
        int digitSum = 0;
        foreach (char digitChar in numStr) {
            digitSum += digitChar - '0';
        }
        return digitSum % 9 == 0 && int.Parse(numStr.Substring(numStr.Length - 3)) % 27 == 0;
    }
  
    static void Main() {
        Console.WriteLine(IsDivisibleBy999(999)); // True
        Console.WriteLine(IsDivisibleBy999(998)); // False
        Console.WriteLine(IsDivisibleBy999(9987)); // False
    }
}


Javascript




function is_divisible_by_999(num) {
    // Convert the input number to a string
    var num_str = num.toString();
  
    // Initialize a variable to hold the sum of the digits
    var sum = 0;
  
    // Iterate over each character in the string representation of the number
    for (var i = 0; i < num_str.length; i++) {
        // Add the numeric value of the current digit to the sum variable
        sum += parseInt(num_str[i]);
    }
  
    // Check if the sum is divisible by 9 and the last three digits of the number are divisible by 27
    return (sum % 9 == 0 && parseInt(num_str.substring(num_str.length - 3)) % 27 == 0);
}
  
// Test the function with some sample inputs
console.log(is_divisible_by_999(999));   // true
console.log(is_divisible_by_999(998));   // false
console.log(is_divisible_by_999(9987));  // false
  
// This code is contributed by bhardwajji.


Output

True
False
False

Time complexity: O(1),
Auxiliary Space : O(1) 

Method 4: Using string manipulation 

1. Convert the number to a string.
2. Find the sum of every third digit from the right end to the left end.
3. If the sum is divisible by 3, then the original number is divisible by 999.

Java




public class GFG {
    public static boolean isDivisibleBy999(int n) {
        String s = Integer.toString(n);
        int l = s.length();
        int sum = 0;
        for (int i = l - 1; i >= 0; i -= 3) {
            int j = Math.max(i - 2, -1);
            sum += Integer.parseInt(s.substring(j + 1, i + 1));
        }
        return sum % 3 == 0;
    }
  
    public static void main(String[] args) {
        int n1 = 998;
        int n2 = 999;
        System.out.println(isDivisibleBy999(n1));
        System.out.println(isDivisibleBy999(n2));
    }
}


Python3




# python code to check if given number is divisible by 998 or not
def is_divisible_by_999(n):
    s = str(n)
    l = len(s)
    sum = 0
    for i in range(l-1, -1, -3):
        j = max(i-2, -1)
        sum += int(s[j+1:i+1])
    return sum % 3 == 0
  
# Example usage
n1 = 998
n2 = 999
print(is_divisible_by_999(n1))  # Output: True
print(is_divisible_by_999(n2))  # Output: False


C++




#include <iostream>
#include <string>
  
using namespace std;
  
bool isDivisibleBy999(int n)
{
    string s = to_string(n);
    int l = s.length();
    int sum = 0;
    for (int i = l - 1; i >= 0; i -= 3) {
        int j = max(i - 2, -1);
        sum += stoi(s.substr(j + 1, i - j));
    }
    return sum % 3 == 0;
}
  
int main()
{
    int n1 = 998;
    int n2 = 999;
    cout << isDivisibleBy999(n1) << endl;
    cout << isDivisibleBy999(n2) << endl;
    return 0;
}


C#




using System;
  
public class GFG {
    public static bool IsDivisibleBy999(int n) {
        string s = n.ToString();
        int l = s.Length;
        int sum = 0;
        for (int i = l - 1; i >= 0; i -= 3) {
            int j = Math.Max(i - 2, -1);
            sum += int.Parse(s.Substring(j + 1, i - j));
        }
        return sum % 3 == 0;
    }
  
    public static void Main(string[] args) {
        int n1 = 998;
        int n2 = 999;
        Console.WriteLine(IsDivisibleBy999(n1));
        Console.WriteLine(IsDivisibleBy999(n2));
    }
}
// This code is contributed by shiv1o43g


Javascript




// JavaScript code to check if given number is divisible by 998 or not
function isDivisibleBy998(n) {
  let s = n.toString();
  let l = s.length;
  let sum = 0;
  for (let i = l - 1; i >= 0; i -= 3) {
    let j = Math.max(i - 2, -1);
    sum += parseInt(s.substring(j + 1, i + 1));
  }
  return sum % 3 === 0;
}
  
// Example usage
let n1 = 998;
let n2 = 999;
console.log(isDivisibleBy998(n1));  
console.log(isDivisibleBy998(n2));  


Output

False
True

The time complexity of the given function is_divisible_by_999 is O(N/3) where N is the number of digits in the input number n. This is because the loop iterates over every third digit of the input number, and performs constant time operations (such as string slicing and integer conversion) on each iteration.

The auxiliary space used by the function is O(1), since it uses a constant amount of extra space to store the loop variables and the running sum.

More Divisibility Algorithms.
 



Similar Reads

Check if a large number is divisibility by 15
Given a very large number. Check its divisibility by 15. Examples: Input: "31"Output: NoInput : num = "156457463274623847239840239 402394085458848462385346236 482374823647643742374523747 264723762374620"Output: YesGiven number is divisible by 15A number is divisible by 15 if it is divisible by 5 (if the last digit is 5 or 0), and it is divisible by
5 min read
Divisibility by 12 for a large number
Given a large number, the task is to check whether the number is divisible by 12 or not. Examples : Input : 12244824607284961224 Output : Yes Input : 92387493287593874594898678979792 Output : No Method 1: This is a very simple approach. if a number is divisible by 4 and 3 then the number is divisible by 12. Point 1. If the last two digits of the nu
8 min read
Mathematical Algorithms - Divisibility and Large Numbers
Divisibility is about whether one number can be divided by another number without leaving any remainder. This is an important concept in math. In this article, we'll look at the different ways to test if a number is divisible by another number. We'll explain the techniques used to quickly figure out if a number can be divided evenly, without any le
6 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
Check if any permutation of a large number is divisible by 8
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 i
10 min read
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
Multiply large integers under large modulo
Given an integer a, b, m. Find (a * b ) mod m, where a, b may be large and their direct multiplication may cause overflow. However, they are smaller than half of the maximum allowed long long int value. Examples: Input: a = 426, b = 964, m = 235Output: 119Explanation: (426 * 964) % 235 = 410664 % 235 = 119 Input: a = 10123465234878998, b = 65746311
7 min read
Check divisibility of product of elements of arr1 and arr2
Given two arrays arr1[] and arr2[], the task is to check if the product of elements of arr1 is divisible by the product of elements of arr2, print "1", else print "0". Examples: Input: arrayA = [20, 40, 5, 8] arrayB = [2, 16, 10, 50, 1]Output: 1Explanation: Product of elements of arrayA = 20 * 40 * 5 * 8 = 32000Product of elements of arrayB = 2 * 1
10 min read
Check divisibility of binary string by 2^k
Given a binary string and a number k, the task is to check whether the binary string is evenly divisible by 2k or not. Examples : Input : 11000 k = 2Output : YesExplanation :(11000)2 = (24)1024 is evenly divisible by 2k i.e. 4. Input : 10101 k = 3Output : NoExplanation : (10101)2 = (21)1021 is not evenly divisible by 2k i.e. 8.Naive Approach: Compu
10 min read
Check divisibility by 7
Given a number N, the task is to check if it is divisible by 7 or not.Note: You are not allowed to use the modulo operator, floating point arithmetic is also not allowed. Naive approach: A simple method is repeated subtraction. Following is another interesting method.Divisibility by 7 can be checked by a recursive method. A number of the form 10a +
6 min read
Check divisibility in a binary stream
Stream of binary number is coming, the task is to tell the number formed so far is divisible by a given number n. At any given time, you will get 0 or 1 and tell whether the number formed with these bits is divisible by n or not. Generally, e-commerce companies ask this type of questions. It was asked me in Microsoft interview. Actually that questi
11 min read
Check the divisibility of Hexadecimal numbers
Given a string S consisting of a large hexadecimal number, the task is to check its divisibility by a given decimal number M. If divisible then print Yes else print No. Examples: Input: S = "10", M = 4 Output: Yes 10 is 16 in decimal and (16 % 4) = 0 Input: S = "10", M = 5 Output: No Approach 1: In this approach, we first convert the hexadecimal nu
9 min read
Find number of integers that can be obtained by replacing ? in given string for perfect divisibility by 9
Given a String S of length N. S contains 'X' at some places. Then your task is to output the number distinct of integers that can be formed by replacing 'X' from the range [0, 9] and the formed integer leaves the remainder 0 after dividing them by 9. Note: Numbers with leading 0s are not allowed to form. Examples: Input: N = 2, S = XXOutput: 10Expl
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
Find operations for Array Divisibility by Power of 2
Given an array of size n, the task is to find the minimum number of operations required in the array such that the product of all array elements is divisible by nth power of 2. In one operation, you can select any index i and multiply ai by i, you can perform an operation on a particular index at most 1 time. (Follow 1-based indexing) Examples: Inp
12 min read
Repeated Unit Divisibility
A number which consists entirely repeated number of times one is said to be Repeated Unit. We shall define R(k) of length k repeated unit number. For example, R(6) = 111111. For a given number n, a positive integer and GCD(n, 10) = 1, there exists a value k such that R(k) is divisible by n. Now let A(n) be the least such value of k i.e. A(n) = k. T
5 min read
Divisibility by 3 where each digit is the sum of all prefix digits modulo 10
Given K, number of digits, and d0 and d1 as the two digits to form the k-sized integer. Task is to check whether the k-sized number formed using d0 and d1 is divisible by 3 or not. For each i, di is the sum of all preceding (more significant) digits, modulo 10 — more formally, the following formula must hold : [Tex]\huge{d_{i} = \sum_{j = 0}^{i - 1
11 min read
Counting Arrays with divisibility constraint
Given two integers X and Y, the task is to find the number of different arrays that can be constructed of size largest possible size that follow the conditions below: Every element of the array should not be less than X and should not be greater than Y.Every element should occur at most once in the array.Let Ai and Aj be two elements of the array w
9 min read
Maximize profit when divisibility by two numbers have associated profits
Given five integers N, A, B, X and Y. The task is to find the maximum profit obtained from the numbers from the range [1, N]. If a positive number is divisible by A then the profit increases by X and if a positive number is divisible by B then the profit increases by Y. Note: Profit from a positive number can be added at most once. Examples: Input:
9 min read
Maximum Subarray Length with Divisibility and Sum Constraint
Given two integers N, K, and two arrays A and B each of size N, such that for every index i, A[i] lies between [1, 104] and B[i] lies between [1, 109]. Find the maximum subarray length [l, r] such that: For each index i which lies between [l, r-1], B[i] is divisible by B[i+1] andThe sum of all the elements in the range [l, r] in array A &lt;= K.Exa
8 min read
Sub-string Divisibility by 3 Queries
Given a large number, n (having number digits up to 10^6) and various queries of the form : Query(l, r) : find if the sub-string between the indices l and r (Both inclusive) are divisible by 3.Examples: Input: n = 12468236544 Queries: l=0 r=1 l=1 r=2 l=3 r=6 l=0 r=10 Output: Divisible by 3 Divisible by 3 Not divisible by 3 Divisible by 3 Explanatio
6 min read
Sub-string Divisibility by 11 Queries
Given a large number, n (having number digits up to 10^6) and various queries of the below form : Query(l, r) : find if the sub-string between the indices l and r (Both inclusive) are divisible by 11. Examples: Input: n = 122164154695 Queries: l = 0 r = 3, l = 1 r = 2, l = 5 r = 9, l = 0 r = 11 Output: True False False True Explanation: In the firs
8 min read
Maximum path sum for each position with jumps under divisibility condition
Given an array of n positive integers. Initially we are at first position. We can jump to position y (1 &lt;= y &lt;= n) from position x (1 &lt;= x &lt;= n) if x divides y and x &lt; y. The task is to print maximum sum path ending at every position x. Note : Since first element is at position 1, we can jump to any position from here as 1 divides al
10 min read
Divisibility by 64 with removal of bits allowed
Given a binary string, we need to check whether that number is divisible by 64 or not after removing of some bits. If yes then print "possible" else "not possible". We cannot make number 0 to make it divisible.Example : Input: 100010001 Output: Possible Explanation: We can get string 1 000 000 after removing two ones which is a representation of nu
5 min read
CSES Solutions - Subarray Divisibility
Given an array arr[] of N integers, your task is to count the number of subarrays where the sum of values is divisible by N. Examples: Input: N = 5, arr[] = {3, 1, 2, 7, 4}Output: 1Explanation: There is only 1 subarray with sum divisible by 5, subarray {1, 2, 7}, sum = 10 and 10 is divisible by 5. Input: N = 5, arr[] = {1, 2, 3, 4, 5}Output: 4Expla
6 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
Check whether the cost of going from any node to any other node via all possible paths is same
Given adjacency list representation of a directed graph, the task is to check whether the cost of going from any vertex to any other vertex via all possible paths is equal or not. If there is a cost c for going from vertex A to vertex B, then the cost to travel from vertex B to vertex A will be -c. Examples: Input: arr[][] = {{0, 2, 0, 1}, {-2, 0,
9 min read
Check if any K ranges overlap at any point
Given N ranges [L, R] and an integer K, the task is to check if there are any K ranges that overlap at any point. Examples: Input: ranges[][] = {{1, 3}, {2, 4}, {3, 4}, {7, 10}}, K = 3 Output: Yes 3 is a common point among the ranges {1, 3}, {2, 4} and {3, 4}. Input: ranges[][] = {{1, 2}, {3, 4}, {5, 6}, {7, 8}}, K = 2 Output: No Recommended: Pleas
13 min read
Check if a large number can be divided into two or more segments of equal sum
Given a very large Number N. The task is to check if the number can be divided into two or more segments of an equal sum. Examples: Input: N = 73452 Output: Yes Segments of {7}, {3, 4}, {5, 2} which has equal sum of 7 Input: N = 1248 Output: No The following steps can be followed to solve the problem: Since the number can be large, the number is in
8 min read
Practice Tags :