Given two integer N and D where 1 ≤ N ≤ 1018, the task is to find the sum of all the integers from 1 to N whose unit digit is D.
Input: N = 30, D = 3
3 + 13 + 23 = 39
Input: N = 5, D = 7
Approach: In Set 1 we saw two basic approaches to find the required sum, but the complexity is O(N) which will take more time for larger N. Here’s an even efficient approach, suppose we are given N = 30 and D = 3:
sum = 3 + 13 + 23
sum = 3 + (10 + 3) + (20 + 3)
sum = 3 * (3) + (10 + 20)
From the above observation, we can find the sum following the steps below:
- Decrement N until N % 10 != D.
- Find K = N / 10.
- Now, sum = (K + 1) * D + (((K * 10) + (10 * K * K)) / 2).
Below is the implementation of the above approach:
- Sum of integers upto N with given unit digit
- Count 'd' digit positive integers with 0 as a digit
- Count numbers with unit digit k in given range
- Find unit digit of x raised to power y
- Find the unit place digit of sum of N factorials
- Number of N digit integers with weight W
- Count of m digit integers that are divisible by an integer n
- Count positive integers with 0 as a digit and maximum 'd' digits
- Integers from the range that are composed of a single distinct digit
- Median in a stream of integers (running integers)
- Count of Numbers in Range where first digit is equal to last digit of the number
- Largest number less than N with digit sum greater than the digit sum of N
- Count n digit numbers not having a particular digit
- Check if frequency of each digit is less than the digit
- Sum of the series (1*2) + (2*3) + (3*4) + ...... upto n terms
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.