给定正整数N ,任务是计算从1到N的所有整数之和,但不包括2的乘方幂。
例子:
Input: N = 2
Output: 0
Input: N = 1000000000
Output: 499999998352516354
天真的方法:
天真的方法是迭代从1到N的每个数字,并通过排除作为2的乘方幂的数字来计算变量中的总和。但是要计算总和为10 ^ 9的数字,上述方法将给出时间限制错误。
时间复杂度: O(N)
高效方法:
要找到所需的总和,请执行以下步骤:
- 使用本文讨论的公式在O(1)时间内找到直到N的所有数字的总和。
- 由于2的所有完美幂的和形成几何级数。因此,通过以下公式计算所有小于N的2的幂的和:
The number of element with perfect power of 2 less than N is given by log2N,
Let r = log2N
And the sum of all numbers which are perfect power of 2 is given by 2r – 1.
- 从前N个数字的总和中减去上面计算的2的所有完美幂的总和,即可得出结果。
下面是上述方法的实现:
C++
// C++ implementation of the
// approach
#include
using namespace std;
// Function to find the required
// summation
void findSum(int N)
{
// Find the sum of first N
// integers using the formula
int sum = (N) * (N + 1) / 2;
int r = log2(N) + 1;
// Find the sum of numbers
// which are exact power of
// 2 by using the formula
int expSum = pow(2, r) - 1;
// Print the final Sum
cout << sum - expSum << endl;
}
// Driver's Code
int main()
{
int N = 2;
// Function to find the
// sum
findSum(N);
return 0;
}
Java
// Java implementation of the above approach
import java.lang.Math;
class GFG{
// Function to find the required
// summation
public static void findSum(int N)
{
// Find the sum of first N
// integers using the formula
int sum = (N) * (N + 1) / 2;
int r = (int)(Math.log(N) /
Math.log(2)) + 1;
// Find the sum of numbers
// which are exact power of
// 2 by using the formula
int expSum = (int)(Math.pow(2, r)) - 1;
// Print the final Sum
System.out.println(sum - expSum);
}
// Driver Code
public static void main(String[] args)
{
int N = 2;
// Function to find the sum
findSum(N);
}
}
// This code is contributed by divyeshrabadiya07
Python3
# Python 3 implementation of the
# approach
from math import log2,pow
# Function to find the required
# summation
def findSum(N):
# Find the sum of first N
# integers using the formula
sum = (N) * (N + 1) // 2
r = log2(N) + 1
# Find the sum of numbers
# which are exact power of
# 2 by using the formula
expSum = pow(2, r) - 1
# Print the final Sum
print(int(sum - expSum))
# Driver's Code
if __name__ == '__main__':
N = 2
# Function to find the
# sum
findSum(N)
# This code is contributed by Surendra_Gangwar
C#
// C# implementation of the above approach
using System;
class GFG{
// Function to find the required
// summation
public static void findSum(int N)
{
// Find the sum of first N
// integers using the formula
int sum = (N) * (N + 1) / 2;
int r = (int)(Math.Log(N) /
Math.Log(2)) + 1;
// Find the sum of numbers
// which are exact power of
// 2 by using the formula
int expSum = (int)(Math.Pow(2, r)) - 1;
// Print the final Sum
Console.Write(sum - expSum);
}
// Driver Code
public static void Main(string[] args)
{
int N = 2;
// Function to find the sum
findSum(N);
}
}
// This code is contributed by rutvik_56
Javascript
输出:
0
时间复杂度: O(1)