Sum of integers upto N with given unit digit (Set 2)
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.
Examples:
Input: N = 30, D = 3
Output: 39
3 + 13 + 23 = 39
Input: N = 5, D = 7
Output: 0
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:
C++
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
ll getSum(ll n, int d)
{
if (n < d)
return 0;
while (n % 10 != d)
n--;
ll k = n / 10;
return (k + 1) * d + (k * 10 + 10 * k * k) / 2;
}
int main()
{
ll n = 30;
int d = 3;
cout << getSum(n, d);
return 0;
}
|
Java
import java.io.*;
class GFG {
static long getSum( long n, int d)
{
if (n < d)
return 0 ;
while (n % 10 != d)
n--;
long k = n / 10 ;
return (k + 1 ) * d + (k * 10 + 10 * k * k) / 2 ;
}
public static void main (String[] args) {
long n = 30 ;
int d = 3 ;
System.out.println(getSum(n, d)); }
}
|
Python3
def getSum(n, d) :
if (n < d) :
return 0
while (n % 10 ! = d) :
n - = 1
k = n / / 10
return ((k + 1 ) * d +
(k * 10 + 10 * k * k) / / 2 )
if __name__ = = "__main__" :
n = 30
d = 3
print (getSum(n, d))
|
C#
class GFG {
static int getSum( int n, int d)
{
if (n < d)
return 0;
while (n % 10 != d)
n--;
int k = n / 10;
return (k + 1) * d + (k * 10 + 10 * k * k) / 2;
}
public static void Main () {
int n = 30;
int d = 3;
System.Console.WriteLine(getSum(n, d)); }
}
|
PHP
<?php
function getSum( $n , $d )
{
if ( $n < $d )
return 0;
while ( $n % 10 != $d )
$n --;
$k = (int)( $n / 10);
return ( $k + 1) * $d +
( $k * 10 + 10 * $k * $k ) / 2;
}
$n = 30;
$d = 3;
echo getSum( $n , $d );
?>
|
Javascript
<script>
function getSum(n, d)
{
if (n < d)
return 0;
while (n % 10 != d)
n--;
k = parseInt(n / 10);
return (k + 1) * d +
(k * 10 + 10 * k * k) / 2;
}
let n = 30;
let d = 3;
document.write( getSum(n, d));
</script>
|
Time Complexity: O(n) //since one traversal of the loop till the number is required to complete all operations hence the overall time required by the algorithm is linear
Auxiliary Space: O(1) // since no extra array is used so the space taken by the algorithm is constant
Last Updated :
21 Aug, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...