给定数字a并限制N。找出最多N的倍数之和。
例子 :
Input : a = 4, N = 23
Output : sum = 60
[Multiples : 4, 8, 12, 16, 20]
Input :a = 7, N = 49
Output :sum = 196
[Multiples: 7, 14, 21, 28, 35, 42, 49]
基本思想是从i = a迭代到i = n,i ++并检查i%a == 0是否为零,如果为零,则将i加到sum(最初为sum = 0),这样我们就得到了总和。将花费O(n)时间。
我们可以将循环修改为i = a,i <= n,i = i + a以减少迭代次数,但是如果a的m倍,也将花费O(m)时间。
为了得到O(1)时间的结果,我们可以使用n个自然数之和的公式。
a = 4且N = 23,即a的倍数,m = N / a(整数除法)。倍数是4、8、12、16、20。
我们可以将其写为4 X [1、2、3、4、5]。这样我们就可以得到倍数之和:
sum = a * (Summation of 1 to m [natural numbers from 1 to m])
sum = 4 * (m*(m+1) / 2)
sum = 4 * (5*6 / 2) = 4 * 15 = 60
C++
// C++ program to find sum of multiples of a number
// up to N efficiently
#include
using namespace std;
// Function for calculating sum of multiples of
// a upto N
int calculate_sum(int a, int N)
{
// Number of multiples
int m = N / a;
// sum of first m natural numbers
int sum = m * (m + 1) / 2;
// sum of multiples
int ans = a * sum;
return ans;
}
// Driver code
int main()
{
int a = 7, N = 49;
cout << "Sum of multiples of "
<< a << " up to " << N << " = "
<< calculate_sum(a, N) << endl;
return 0;
}
Java
// Java program to find sum of multiples
// of a number up to N efficiently
class GFG {
// Function for calculating sum
// of multiples of a upto N
static int calculate_sum(int a, int N) {
// Number of multiples
int m = N / a;
// sum of first m natural numbers
int sum = m * (m + 1) / 2;
// sum of multiples
int ans = a * sum;
return ans;
}
// Driver code
public static void main(String[] args) {
int a = 7, N = 49;
System.out.println("Sum of multiples of " + a +
" up to " + N + " = " +
calculate_sum(a, N));
}
}
// This code is contributed by Anant Agarwal.
Python3
"""Python program to find sum of
multiples of a number up to N"""
# Calculates sum of multiples of
# a number upto N
def calculate_sum(a, N):
# Number of multiples
m = N / a
# sum of first m natural numbers
sum = m * (m + 1) / 2
# sum of multiples
ans = a * sum
print("Sum of multiples of ", a,
" up to ", N, " = ", ans)
# Driver Code
calculate_sum(7, 49)
# This code is contributed by Abhishek Agrawal.
C#
// C# program to find sum of multiples
// of a number up to N efficiently
using System;
class GFG {
// Function for calculating sum
// of multiples of a upto N
static int calculate_sum(int a, int N)
{
// Number of multiples
int m = N / a;
// sum of first m natural numbers
int sum = m * (m + 1) / 2;
// sum of multiples
int ans = a * sum;
return ans;
}
// Driver code
public static void Main()
{
int a = 7, N = 49;
Console.WriteLine("Sum of multiples of " + a +
" up to " + N + " = " + calculate_sum(a, N));
}
}
// This code is contributed by vt_m.
PHP
Javascript
输出 :
Sum of multiples of 7 upto 49 = 196