在给定范围LR的情况下,找到范围LR内可被6整除的所有数字的总和
L和R非常大。
例子:
Input : 1 20
Output : 36
Explanation: 6 + 12 + 18 = 36
Input : 5 7
Output : 6
Explanation: 6 is the only divisible number
in range 5-7
一个简单的方法是从L到R循环运行,并对所有可被6整除的数字求和。
一种有效的方法是将所有可被6整除的数字相加,直到R,再将所有可被6整除的数字相加,直到L-1。然后减法将是答案。
总和= 6 + 12 + 8 + …….(R / 6)项。
总和= 6(1 + 2 + 3…R / 6项)
sumR = 3 * (R/6) * (R/6+1)
同样,我们得到
sumL as 3 * ((L-1)/6) * ((L-1/6)+1)
最终答案为sumR – sumL。
C++
// CPP program to find sum of numbers divisible
// by 6 in a given range.
#include
using namespace std;
// function to calculate the sum of
// all numbers divisible by 6 in range L-R..
int sum(int L, int R)
{
// no of multiples of 6 upto r
int p = R / 6;
// no of multiples of 6 upto l-1
int q = (L - 1) / 6;
// summation of all multiples of 6 upto r
int sumR = 3 * (p * (p + 1));
// summation of all multiples of 6 upto l-1
int sumL = (q * (q + 1)) * 3;
// returns the answer
return sumR - sumL;
}
// driver program to test the above function
int main()
{
int L = 1, R = 20;
cout << sum(L, R);
return 0;
}
Java
// Java program to find sum of numbers
// divisible by 6 in a given range.
import java.io.*;
class GFG {
// function to calculate the sum
// of all numbers divisible by 6
// in range L-R..
static int sum(int L, int R)
{
// no of multiples of 6 upto r
int p = R / 6;
// no of multiples of 6 upto l-1
int q = (L - 1) / 6;
// summation of all multiples of
// 6 upto r
int sumR = 3 * (p * (p + 1));
// summation of all multiples of
// 6 upto l-1
int sumL = (q * (q + 1)) * 3;
// returns the answer
return sumR - sumL;
}
// driver program
public static void main(String[] args)
{
int L = 1, R = 20;
System.out.println(sum(L, R));
}
}
// This code is contributed by Prerna Saini
Python
# Python3 program to find sum of numbers divisible
# by 6 in a given range.
def sumDivisible(L, R):
# no of multiples of 6 upto r
p = int(R/6)
# no of multiples of 6 upto l-1
q = int((L-1)/6)
# summation of all multiples of 6 upto r
sumR = 3 * (p * (p + 1))
# summation of all multiples of 6 upto l-1
sumL = (q * (q + 1)) * 3
# returns the answer
return sumR - sumL
# driver code
L = 1
R = 20
print(sumDivisible(L,R))
# This code is contributed by 'Abhishek Sharma 44'.
C#
// C# program to find sum of numbers
// divisible by 6 in a given range.
using System;
class GFG {
// function to calculate the sum
// of all numbers divisible by 6
// in range L-R..
static int sum(int L, int R)
{
// no of multiples of 6 upto r
int p = R / 6;
// no of multiples of 6 upto l-1
int q = (L - 1) / 6;
// summation of all multiples of
// 6 upto r
int sumR = 3 * (p * (p + 1));
// summation of all multiples of
// 6 upto l-1
int sumL = (q * (q + 1)) * 3;
// returns the answer
return sumR - sumL;
}
// driver program
public static void Main()
{
int L = 1, R = 20;
Console.WriteLine(sum(L, R));
}
}
// This code is contributed by Anant Agarwal.
PHP
Javascript
// Javascript program to find sum of numbers divisible
// by 6 in a given range.
输出:
36
时间复杂度:O(1)