Given a range L-R, find the sum of all numbers divisible by 6 in range L-R
L and R are very large.
Examples:
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
A naive approach is be to run a loop from L to R and sum up all the numbers divisible by 6.
An efficient approach is to sum all the numbers divisible by 6 up to R in sum, and sum all numbers divisible by 6 up to L-1. And then there subtraction will be the answer.
sum = 6 + 12 + 8 + …….(R/6)terms.
sum = 6(1 + 2 + 3……R/6 terms)
sumR = 3 * (R/6) * (R/6+1)
similarly we get
sumL as 3 * ((L-1)/6) * ((L-1/6)+1)
and the final answer as sumR – sumL.
C++
#include <bits/stdc++.h>
using namespace std;
int sum( int L, int R)
{
int p = R / 6;
int q = (L - 1) / 6;
int sumR = 3 * (p * (p + 1));
int sumL = (q * (q + 1)) * 3;
return sumR - sumL;
}
int main()
{
int L = 1, R = 20;
cout << sum(L, R);
return 0;
}
|
Java
import java.io.*;
class GFG {
static int sum( int L, int R)
{
int p = R / 6 ;
int q = (L - 1 ) / 6 ;
int sumR = 3 * (p * (p + 1 ));
int sumL = (q * (q + 1 )) * 3 ;
return sumR - sumL;
}
public static void main(String[] args)
{
int L = 1 , R = 20 ;
System.out.println(sum(L, R));
}
}
|
Python
def sumDivisible(L, R):
p = int (R / 6 )
q = int ((L - 1 ) / 6 )
sumR = 3 * (p * (p + 1 ))
sumL = (q * (q + 1 )) * 3
return sumR - sumL
L = 1
R = 20
print (sumDivisible(L,R))
|
C#
using System;
class GFG {
static int sum( int L, int R)
{
int p = R / 6;
int q = (L - 1) / 6;
int sumR = 3 * (p * (p + 1));
int sumL = (q * (q + 1)) * 3;
return sumR - sumL;
}
public static void Main()
{
int L = 1, R = 20;
Console.WriteLine(sum(L, R));
}
}
|
PHP
<?php
function sum( $L , $R )
{
$p = intval ( $R / 6);
$q = intval (( $L - 1) / 6);
$sumR = intval (3 * ( $p * ( $p + 1)));
$sumL = intval (( $q * ( $q + 1)) * 3);
return $sumR - $sumL ;
}
$L = 1;
$R = 20;
echo sum( $L , $R );
?>
|
Javascript
<script>
function sum(L, R)
{
let p = Math.floor(R / 6);
let q = Math.floor((L - 1) / 6);
let sumR = Math.floor(3 * (p * (p + 1)));
let sumL = Math.floor((q * (q + 1)) * 3);
return sumR - sumL;
}
let L = 1, R = 20;
document.write(sum(L, R));
</script>
|
Output:
36
Time Complexity: O(1), as we are not using any loop or recursion to traverse.
Auxiliary Space: O(1), as we are not using any extra space.