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.
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 Explanation: In the first query, 12 is divisible by 3 In the second query, 24 is divisible by 3 and so on.
We know that any number is divisible by 3 if the sum of its digits is divisible by 3. Hence the idea is to pre-process an auxiliary array that would store the sum of digits.
Mathematically, sum = 0 and for i from 0 to number of digits of number: sum[i+1] = sum[i]+ toInt(n[i]) where toInt(n[i]) represents the integer value of i'th digit of n
Once our auxiliary array is processed, we can answer each query in O(1) time, because the substring from indices l to r would be divisible by 3 only if, (sum[r+1]-sum[l])%3 == 0
Below is a the implementation program for the same.
Divisible by 3 Divisible by 3 Not divisible by 3 Divisible by 3
This article is contributed by Ashutosh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Sub-string Divisibility by 11 Queries
- Check divisibility by 7
- Divisibility by 12 for a large number
- Repeated Unit Divisibility
- To check divisibility of any large number by 999
- Check divisibility in a binary stream
- Check if a large number is divisibility by 15
- Divisibility by 64 with removal of bits allowed
- Check the divisibility of Hexadecimal numbers
- Divisibility by 3 where each digit is the sum of all prefix digits modulo 10
- Maximize profit when divisibility by two numbers have associated profits
- Maximum path sum for each position with jumps under divisibility condition
- Find the Substring with maximum product
- Print all substring of a number without any conversion
- Smallest non-zero substring which has any permutation divisible by 2^K
- XOR of a submatrix queries
- Lexicographically smallest substring with maximum occurrences containing a's and b's only
- Length of the longest substring with no consecutive same letters
- Find the String having each substring with exactly K distinct characters
- Number of binary strings such that there is no substring of length ≥ 3