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:
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.
- Sum of integers upto N with given unit digit
- Sum of product of all integers upto N with their count of divisors
- Construct a sequence from given frequencies of N consecutive integers with unit adjacent difference
- Count permutations of all integers upto N that can form an acyclic graph based on given conditions
- Find the unit place digit of sum of N factorials
- Count 'd' digit positive integers with 0 as a digit
- Count numbers with unit digit k in given range
- Count of N-digit numbers having digit XOR as single digit
- Find unit digit of x raised to power y
- Minimum count of numbers required with unit digit X that sums up to N
- Largest number less than N with digit sum greater than the digit sum of N
- Sum of last digit of all integers from 1 to N divisible by M
- Find N fractions that sum upto a given fraction N/D
- Sum of largest divisor of numbers upto N not divisible by given prime number P
- Count numbers in a range with digit sum divisible by K having first and last digit different
- Median in a stream of integers (running integers)
- Mode in a stream of integers (running integers)
- Lexicographically smallest permutation of size A having B integers exceeding all preceeding integers
- Count positive integers with 0 as a digit and maximum 'd' digits
- Count of m digit integers that are divisible by an integer n
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.