给定一个整数N ,任务是计算从1到N的所有i的总和,以使(2 i +1)%3 = 0 。
例子:
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
方法:如果我们仔细观察,我将永远是一个奇数,即1、3、5、7…..。我们将使用公式计算前n个奇数之和,即n * n 。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the required sum
int sumN(int n)
{
// Total odd numbers from 1 to n
n = (n + 1) / 2;
// Sum of first n odd numbers
return (n * n);
}
// Driver code
int main()
{
int n = 3;
cout << sumN(n);
return 0;
}
Java
// Java implementation of the approach
class GFG {
// Function to return the required sum
static int sum(int n)
{
// Total odd numbers from 1 to n
n = (n + 1) / 2;
// Sum of first n odd numbers
return (n * n);
}
// Driver code
public static void main(String args[])
{
int n = 3;
System.out.println(sum(n));
}
}
Python3
# Python3 implementation of the approach
# Function to return the required sum
def sumN(n):
# Total odd numbers from 1 to n
n = (n + 1) // 2;
# Sum of first n odd numbers
return (n * n);
# Driver code
n = 3;
print(sumN(n));
# This code is contributed by mits
C#
// C# implementation of the approach
using System;
public class GFG {
// Function to return the required sum
public static int sum(int n)
{
// Total odd numbers from 1 to n
n = (n + 1) / 2;
// Sum of first n odd numbers
return (n * n);
}
// Driver code
public static void Main(string[] args)
{
int n = 3;
Console.WriteLine(sum(n));
}
}
// This code is contributed by Shrikant13
PHP
Javascript
输出:
4
时间复杂度: O(1)