Given a range L-R, find the sum of all numbers divisible by 6 in range L-R
L and R are very large.
Input : 1 20 Output : 36 Explanation: 6 + 12 + 18 = 36 Input : 5 7 Output : 6 Explanation: 6 is the only divisible number in range 5-7
A naive approach is be to run a loop from L to R and sum up all the numbers divisible by 6.
An efficient approach is to sum all the numbers divisible by 6 up to R in sum, and sum all numbers divisible by 6 up to L-1. And then there subtraction will be the answer.
sum = 6 + 12 + 8 + …….(R/6)terms.
sum = 6(1 + 2 + 3……R/6 terms)
sumR = 3 * (R/6) * (R/6+1)
similarly we get
sumL as 3 * ((L-1)/6) * ((L-1/6)+1)
and the final answer as sumR – sumL.
Time Complexity: O(1)
- Sum of all numbers in the given range which are divisible by M
- Numbers that are not divisible by any number in the range [2, 10]
- Count the numbers divisible by 'M' in a given range
- Count numbers in range 1 to N which are divisible by X but not by Y
- Count of all even numbers in the range [L, R] whose sum of digits is divisible by 3
- Count numbers in range L-R that are divisible by all of its non-zero digits
- Count of numbers between range having only non-zero digits whose sum of digits is N and number is divisible by M
- Count integers in the range [A, B] that are not divisible by C and D
- Check if there is any pair in a given range with GCD is divisible by k
- Minimum positive integer divisible by C and is not in range [A, B]
- Number of integers in a range [L, R] which are divisible by exactly K of it's digits
- Maximum positive integer divisible by C and is in the range [A, B]
- Sum of largest divisible powers of p (a prime number) in a range
- Count integers in a range which are divisible by their euler totient value
- Ways to form an array having integers in given range such that total sum is divisible by 2
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.