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
- Find the unit place digit of sum of N factorials
- Find unit digit of x raised to power y
- Count numbers with unit digit k in given range
- Sum of last digit of all integers from 1 to N divisible by M
- Number of N digit integers with weight W
- Count of m digit integers that are divisible by an integer n
- Integers from the range that are composed of a single distinct digit
- Count positive integers with 0 as a digit and maximum 'd' digits
- Median in a stream of integers (running integers)
- Count of Numbers in Range where first digit is equal to last digit of the number
- Find the remainder when First digit of a number is divided by its Last digit
- Largest number less than N with digit sum greater than the digit sum of N
- Count n digit numbers not having a particular digit
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.