📜  前N个自然数之和,该自然数可被2和7整除

📅  最后修改于: 2021-04-23 07:35:24             🧑  作者: Mango

给定数字N。任务是找到所有从1到N的数字之和,这些数字可被2或7整除。
例子

Input : N = 7
Output : 19
sum = 2 + 4 + 6 + 7

Input : N = 14 
Output : 63
sum = 2 + 4 + 6 + 7 + 8 + 10 + 12 + 14

方法:要解决此问题,请执行以下步骤:
->查找可被2整除的数字之和,直到N。用S1表示。
->查找可被7整除的数字之和,直到N。用S2表示。
->查找可被14(2 * 7)整除的数字之和,直到N。用S3表示。
->最终答案将是S1 + S2 – S3。
为了找到总和,我们可以使用AP的一般公式:

Sn = (n/2) * {2*a + (n-1)*d}

对于S1:将被2除以N的总数将为N / 2,而序列将为2、4、6、8…。

Hence, 
S1 = ((N/2)/2) * (2 * 2 + (N/2 - 1) * 2)

对于S2:将被7除以N的总数将是N / 7,而序列将是7、14、21、28,……

Hence, 
S2 = ((N/7)/2) * (2 * 7 + (N/7 - 1) * 7)

对于S3:可被14整除到N的总数为N / 14。

Hence, 
S3 = ((N/14)/2) * (2 * 14 + (N/14 - 1) * 14)

因此,结果将是:

S = S1 + S2 - S3

下面是上述方法的实现:

C++
// C++ program to find sum of numbers from 1 to N
// which are divisible by 2 or 7
#include 
using namespace std;
 
// Function to calculate the sum
// of numbers divisible by 2 or 7
int sum(int N)
{
    int S1, S2, S3;
 
    S1 = ((N / 2)) * (2 * 2 + (N / 2 - 1) * 2) / 2;
    S2 = ((N / 7)) * (2 * 7 + (N / 7 - 1) * 7) / 2;
    S3 = ((N / 14)) * (2 * 14 + (N / 14 - 1) * 14) / 2;
 
    return S1 + S2 - S3;
}
 
// Driver code
int main()
{
    int N = 20;
 
    cout << sum(N);
 
    return 0;
}


Java
// Java  program to find sum of
// numbers from 1 to N which
// are divisible by 2 or 7
 
import java.io.*;
 
class GFG {
// Function to calculate the sum
// of numbers divisible by 2 or 7
public static int sum(int N)
{
    int S1, S2, S3;
 
    S1 = ((N / 2)) * (2 * 2 +
        (N / 2 - 1) * 2) / 2;
    S2 = ((N / 7)) * (2 * 7 +
        (N / 7 - 1) * 7) / 2;
    S3 = ((N / 14)) * (2 * 14 +
        (N / 14 - 1) * 14) / 2;
 
    return S1 + S2 - S3;
}
 
// Driver code
    public static void main (String[] args) {
 
    int N = 20;
    System.out.println( sum(N));
    }
}
 
// This code is contributed by ajit


Python3
# Python3 implementation of
# above approach
 
# Function to calculate the sum
# of numbers divisible by 2 or 7
def sum(N):
     
    S1 = ((N // 2)) * (2 * 2 + (N // 2 - 1) * 2) // 2
    S2 = ((N // 7)) * (2 * 7 + (N // 7 - 1) * 7) // 2
    S3 = ((N // 14)) * (2 * 14 + (N // 14 - 1) * 14) // 2
 
    return S1 + S2 - S3
 
 
# Driver code
if __name__=='__main__':
    N = 20
 
    print(sum(N))
 
# This code is written by
# Sanjit_Prasad


C#
// C# program to find sum of
// numbers from 1 to N which
// are divisible by 2 or 7
using System;
 
class GFG
{
// Function to calculate the sum
// of numbers divisible by 2 or 7
public static int sum(int N)
{
    int S1, S2, S3;
 
    S1 = ((N / 2)) * (2 * 2 +
          (N / 2 - 1) * 2) / 2;
    S2 = ((N / 7)) * (2 * 7 +
          (N / 7 - 1) * 7) / 2;
    S3 = ((N / 14)) * (2 * 14 +
          (N / 14 - 1) * 14) / 2;
 
    return S1 + S2 - S3;
}
 
// Driver code
public static int Main()
{
    int N = 20;
    Console.WriteLine( sum(N));
    return 0;
}
}
 
// This code is contributed
// by SoumikMondal


PHP


Javascript


输出:
117