📌  相关文章
📜  i的总和,使得(2 ^ i + 1)%3 = 0,其中i在[1,n]范围内

📅  最后修改于: 2021-04-27 23:01:20             🧑  作者: Mango

给定一个整数N ,任务是计算从1N的所有i的总和,以使(2 i +1)%3 = 0
例子:

方法:如果我们仔细观察,将永远是一个奇数,即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)