给定数字N ,任务是找到N之下3和7的所有倍数的和。
注意:总和中不得重复数字。
例子:
Input: N = 10
Output: 25
3 + 6 + 7 + 9 = 25
Input: N = 24
Output: 105
3 + 6 + 7 + 9 + 12 + 14 + 15 + 18 + 21 = 105
方法:
- 我们知道3的倍数形成AP,因为S 3 = 3 + 6 + 9 + 12 + 15 + 18 + 21 +…
- 并且7的倍数形成AP,因为S 7 = 7 + 14 + 21 + 28 +…
- 现在,总和= S 3 + S 7即3 + 6 + 7 + 9 + 12 + 14 + 15 + 18 + 21 + 21 +…
- 从上一步开始,将21重复两次。实际上,所有21的倍数(或3 * 7)都将被重复,因为它们被计数了两次,一次在系列S 3中,一次在系列S 7中。因此,需要从结果中舍弃21的倍数。
- 因此,最终结果将为S 3 + S 7 – S 21
The formula for the sum of an AP series is :
n * ( a + l ) / 2
Where n is the number of terms, a is the starting term, and l is the last term.
下面是上述方法的实现:
C++
// C++ program to find the sum of all
// multiples of 3 and 7 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 3 and 7 below N
long long sumMultiples(long long n)
{
// Since, we need the sum of
// multiples less than N
n--;
return sumAP(n, 3) + sumAP(n, 7) - sumAP(n, 21);
}
// Driver code
int main()
{
long long n = 24;
cout << sumMultiples(n);
return 0;
}
Java
// Java program to find the sum of all
// multiples of 3 and 7 below N
import java.util.*;
class solution
{
// 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 3 and 7 below N
static long sumMultiples(long n)
{
// Since, we need the sum of
// multiples less than N
n--;
return sumAP(n, 3) + sumAP(n, 7) - sumAP(n, 21);
}
// Driver code
public static void main(String args[])
{
long n = 24;
System.out.println(sumMultiples(n));
}
}
//This code is contributed by Surendra_Gangwar
Python3
# Python3 program to find the sum of
# all multiples of 3 and 7 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 3 and 7 below N
def sumMultiples(n):
# Since, we need the sum of
# multiples less than N
n -= 1;
return int(sumAP(n, 3) +
sumAP(n, 7) -
sumAP(n, 21));
# Driver code
n = 24;
print(sumMultiples(n));
# This code is contributed
# by mits
C#
// C# program to find the sum of all
// multiples of 3 and 7 below N
using System;
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 3 and 7 below N
static long sumMultiples(long n)
{
// Since, we need the sum of
// multiples less than N
n--;
return sumAP(n, 3) + sumAP(n, 7) -
sumAP(n, 21);
}
// Driver code
static public void Main(String []args)
{
long n = 24;
Console.WriteLine(sumMultiples(n));
}
}
// This code is contributed
// by Arnab Kundu
PHP
Javascript
输出:
105
如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。