📜  在N以下找到2和5的所有倍数的总和

📅  最后修改于: 2021-04-21 21:44:48             🧑  作者: Mango

给定数字N。任务是找到N以下2和5的所有倍数的总和(N可能高达10 ^ 10)。

例子

Input : N = 10
Output : 25
Explanation : 2 + 4 + 6 + 8 + 5

Input : N = 20
Output : 110

方法 :
我们知道2的倍数形成AP的原因是:

类似地,5的倍数形成一个AP,如下所示:

现在, Sum(1)+ Sum(2) = 2、4、5、6、8、10、10、12、14、15 …。
在此,重复10。实际上,所有10或2 * 5的倍数都被重复,因为它被计数了两次,一次在2系列中,一次在5系列中。因此,我们将从Sum()中减去10系列的总和。 1)+和(2)。

AP的总和的公式为:

因此,最终答案是:

下面是上述方法的实现:

C++
// CPP program to find the sum of all
// multiples of 2 and 5 below N
 
#include 
using namespace std;
 
// Function to find sum of AP series
long long sumAP(long long n, long long d)
{
    // Number of terms
    n /= d;
 
    return (n) * (1 + n) * d / 2;
}
 
// Function to find the sum of all
// multiples of 2 and 5 below N
long long sumMultiples(long long n)
{
    // Since, we need the sum of
    // multiples less than N
    n--;
 
    return sumAP(n, 2) + sumAP(n, 5) - sumAP(n, 10);
}
 
// Driver code
int main()
{
    long long n = 20;
 
    cout << sumMultiples(n);
 
    return 0;
}


Java
// Java program to find the sum of all
// multiples of 2 and 5 below N
 
class GFG{
// Function to find sum of AP series
static long sumAP(long n, long d)
{
    // Number of terms
    n /= d;
 
    return (n) * (1 + n) * d / 2;
}
 
// Function to find the sum of all
// multiples of 2 and 5 below N
static long sumMultiples(long n)
{
    // Since, we need the sum of
    // multiples less than N
    n--;
 
    return sumAP(n, 2) + sumAP(n, 5) - sumAP(n, 10);
}
 
// Driver code
public static void main(String[] args)
{
    long n = 20;
 
    System.out.println(sumMultiples(n));
}
}
// This code is contributed by mits


Python3
# Python3 program to find the sum of
# all multiples of 2 and 5 below N
 
# Function to find sum of AP series
def sumAP(n, d):
 
    # Number of terms
    n = int(n / d);
 
    return (n) * (1 + n) * (d / 2);
 
# Function to find the sum of all
# multiples of 2 and 5 below N
def sumMultiples(n):
 
    # Since, we need the sum of
    # multiples less than N
    n -= 1;
 
    return (int(sumAP(n, 2) + sumAP(n, 5) -
                              sumAP(n, 10)));
 
# Driver code
n = 20;
 
print(sumMultiples(n));
     
# This code is contributed by mits


C#
// C# program to find the sum of all
// multiples of 2 and 5 below N
 
using System;
 
public class GFG{
     
    // Function to find sum of AP series
static long sumAP(long n, long d)
{
    // Number of terms
    n /= d;
 
    return (n) * (1 + n) * d / 2;
}
 
// Function to find the sum of all
// multiples of 2 and 5 below N
static long sumMultiples(long n)
{
    // Since, we need the sum of
    // multiples less than N
    n--;
 
    return sumAP(n, 2) + sumAP(n, 5) - sumAP(n, 10);
}
 
// Driver code
     
    static public void Main (){
            long n = 20;
 
        Console.WriteLine(sumMultiples(n));
    }
}


PHP


Javascript


输出:
110