Sum of all i such that (2^i + 1) % 3 = 0 where i is in range [1, n]
Last Updated :
20 Aug, 2022
Given an integer N, the task is to calculate the sum of all i from 1 to N such that (2i + 1) % 3 = 0.
Examples:
Input: N = 3
Output: 4
For i = 1, 21 + 1 = 3 is divisible by 3.
For i = 2, 22 + 1 = 5 which is not divisible by 3.
For i = 3, 23 + 1 = 9 is divisible by 3.
Hence, sum = 1 + 3 = 4 (for i = 1, 3)
Input: N = 13
Output: 49
Approach: If we observe carefully then i will always be an odd number i.e. 1, 3, 5, 7, …... We will use the formula for the sum of the first n odd numbers which is n * n.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int sumN( int n)
{
n = (n + 1) / 2;
return (n * n);
}
int main()
{
int n = 3;
cout << sumN(n);
return 0;
}
|
Java
class GFG {
static int sum( int n)
{
n = (n + 1 ) / 2 ;
return (n * n);
}
public static void main(String args[])
{
int n = 3 ;
System.out.println(sum(n));
}
}
|
Python3
def sumN(n):
n = (n + 1 ) / / 2 ;
return (n * n);
n = 3 ;
print (sumN(n));
|
C#
using System;
public class GFG {
public static int sum( int n)
{
n = (n + 1) / 2;
return (n * n);
}
public static void Main( string [] args)
{
int n = 3;
Console.WriteLine(sum(n));
}
}
|
PHP
<?php
function sumN( $n )
{
$n = (int)(( $n + 1) / 2);
return ( $n * $n );
}
$n = 3;
echo sumN( $n );
?>
|
Javascript
<script>
function sumN(n)
{
n = parseInt((n + 1) / 2);
return (n * n);
}
var n = 3;
document.write(sumN(n));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1), since no extra space has been taken.
Share your thoughts in the comments
Please Login to comment...