给定两个整数N和D ,其中1≤N≤10 18 ,任务是找到单位数为D的从1到N的所有整数的和。
例子:
Input: N = 30, D = 3
Output: 39
3 + 13 + 23 = 39
Input: N = 5, D = 7
Output: 0
方法:在集合1中,我们看到了两种基本方法来找到所需的总和,但是复杂度为O(N) ,对于较大的N ,它将花费更多的时间。这是一个甚至有效的方法,假设给定N = 30且D = 3 :
sum = 3 + 13 + 23
sum = 3 + (10 + 3) + (20 + 3)
sum = 3 * (3) + (10 + 20)
从上面的观察中,我们可以按照以下步骤找到总和:
- 减小N直到N%10!= D。
- 求K = N / 10 。
- 现在,总和=(K +1)* D +(((K * 10)+(10 * K * K))/ 2) 。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
#define ll long long int
// Function to return the required sum
ll getSum(ll n, int d)
{
if (n < d)
return 0;
// Decrement N
while (n % 10 != d)
n--;
ll k = n / 10;
return (k + 1) * d + (k * 10 + 10 * k * k) / 2;
}
// Driver code
int main()
{
ll n = 30;
int d = 3;
cout << getSum(n, d);
return 0;
}
Java
// Java implementation of the approach
import java.io.*;
class GFG {
// Function to return the required sum
static long getSum(long n, int d)
{
if (n < d)
return 0;
// Decrement N
while (n % 10 != d)
n--;
long k = n / 10;
return (k + 1) * d + (k * 10 + 10 * k * k) / 2;
}
// Driver code
public static void main (String[] args) {
long n = 30;
int d = 3;
System.out.println(getSum(n, d)); }
}
//This code is contributed by inder_verma..
Python3
# Python3 implementation of the approach
# Function to return the required sum
def getSum(n, d) :
if (n < d) :
return 0
# Decrement N
while (n % 10 != d) :
n -= 1
k = n // 10
return ((k + 1) * d +
(k * 10 + 10 * k * k) // 2)
# Driver code
if __name__ == "__main__" :
n = 30
d = 3
print(getSum(n, d))
# This code is contributed by Ryuga
C#
// C# implementation of the approach
class GFG {
// Function to return the required sum
static int getSum(int n, int d)
{
if (n < d)
return 0;
// Decrement N
while (n % 10 != d)
n--;
int k = n / 10;
return (k + 1) * d + (k * 10 + 10 * k * k) / 2;
}
// Driver code
public static void Main () {
int n = 30;
int d = 3;
System.Console.WriteLine(getSum(n, d)); }
}
//This code is contributed by mits.
PHP
Javascript
输出:
39