Thursday, July 4, 2024
HomeData ModellingData Structure & AlgorithmSum of first N natural numbers with all powers of 2 added...

Sum of first N natural numbers with all powers of 2 added twice

Given an integer N, the task is to calculate the sum of first N natural numbers adding all powers of 2 twice to the sum.
Examples: 
 

Input: N = 4 
Output: 17 
Explanation: 
Sum = 2+4+3+8 = 17 
Since 1, 2 and 4 are 2 0, 2 1 and 2 2 respectively, they are added twice to the sum.
Input: N = 5 
Output: 22 
Explanation: 
The sum is equal to 2+4+3+8+5 = 22, 
because 1, 2 and 4 are 2 0, 2 1 and 2 2 respectively.

Naive Approach: 
The simplest approach to solve this problem is to iterate upto N, and keep calculating the sum by adding every number once except the powers of 2, which needs to be added twice. 
Time Complexity: O(N) 
Auxiliary Space: O(1)
Efficient Approach: 
Follow the steps below to optimize the above approach: 
 

  1. Calculate sum of first N natural numbers by the formula (N * (N + 1)) / 2.
  2. Now, all powers of 2 needs to be added once more. Sum of all powers of 2 up to N can be calculated as 2 log2(N) + 1 – 1
     
  3. Hence, the required sum is: 
     

(N * (N + 1)) / 2 + 2 log2(N) + 1 – 1

Below is the implementation of the above approach:
 

C++




// C++ program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to raise N to the
// power P and return the value
double power(int N, int P)
{
    return pow(N, P);
}
 
// Function to calculate the
// log base 2 of an integer
int Log2(int N)
{
 
    // Calculate log2(N) indirectly
    // using log() method
    int result = (int)(log(N) / log(2));
    return result;
}
 
// Function to calculate and
// return the required sum
double specialSum(int n)
{
 
    // Sum of first N natural
    // numbers
    double sum = n * (n + 1) / 2;
 
    // Sum of all powers of 2
    // up to N
    int a = Log2(n);
    sum = sum + power(2, a + 1) - 1;
 
    return sum;
}
 
// Driver code
int main()
{
    int n = 4;
 
    cout << (specialSum(n)) << endl;
 
    return 0;
}
 
// This code is contributed by divyeshrabadiya07


Java




// Java program to implement
// the above approach
import java.util.*;
import java.lang.Math;
 
class GFG {
 
    // Function to raise N to the
    // power P and return the value
    static double power(int N, int P)
    {
        return Math.pow(N, P);
    }
 
    // Function to calculate the
    // log base 2 of an integer
    public static int log2(int N)
    {
 
        // Calculate log2(N) indirectly
        // using log() method
        int result = (int)(Math.log(N)
                        / Math.log(2));
        return result;
    }
 
    // Function to calculate and
    // return the required sum
    static double specialSum(int n)
    {
 
        // Sum of first N natural
        // numbers
        double sum = n * (n + 1) / 2;
 
        // Sum of all powers of 2
        // up to N
        int a = log2(n);
        sum = sum + power(2, a + 1) - 1;
 
        return sum;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        int n = 4;
 
        System.out.println(specialSum(n));
    }
}


Python3




# Python3 program to implement
# the above approach
import math
 
# Function to raise N to the
# power P and return the value
def power(N, P):
     
    return math.pow(N, P)
 
# Function to calculate the
# log base 2 of an integer
def Log2(N):
     
    # Calculate log2(N) indirectly
    # using log() method
    result = (math.log(N) // math.log(2))
     
    return result
 
# Function to calculate and
# return the required sum
def specialSum(n):
     
    # Sum of first N natural
    # numbers
    sum = n * (n + 1) // 2
 
    # Sum of all powers of 2
    # up to N
    a = Log2(n)
    sum = sum + power(2, a + 1) - 1
     
    return sum
     
# Driver code   
if __name__=="__main__":
     
    n = 4
    print(specialSum(n))
 
# This code is contributed by rutvik_56


C#




// C# program to implement
// the above approach
using System;
class GFG
{
 
    // Function to raise N to the
    // power P and return the value
    static double power(int N, int P)
    {
        return Math.Pow(N, P);
    }
 
    // Function to calculate the
    // log base 2 of an integer
    public static int log2(int N)
    {
 
        // Calculate log2(N) indirectly
        // using log() method
        int result = (int)(Math.Log(N) /
                        Math.Log(2));
        return result;
    }
 
    // Function to calculate and
    // return the required sum
    static double specialSum(int n)
    {
 
        // Sum of first N natural
        // numbers
        double sum = (double)(n) * (n + 1) / 2;
 
        // Sum of all powers of 2
        // up to N
        int a = log2(n);
        sum = (sum) + power(2, a + 1) - 1;
 
        return sum;
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
        int n = 4;
 
        Console.Write(specialSum(n));
    }
}
 
// This code is contributed by Ritik Bansal


Javascript




<script>
 
// Javascript program to implement
// the above approach
 
// Function to raise N to the
// power P and return the value
function power(N, P)
{
    return Math.pow(N, P);
}
 
// Function to calculate the
// log base 2 of an integer
function Log2(N)
{
 
    // Calculate log2(N) indirectly
    // using log() method
    let result = (Math.floor(Math.log(N) / Math.log(2)));
    return result;
}
 
// Function to calculate and
// return the required sum
function specialSum(n)
{
 
    // Sum of first N natural
    // numbers
    let sum = n * (n + 1) / 2;
 
    // Sum of all powers of 2
    // up to N
    let a = Log2(n);
    sum = sum + power(2, a + 1) - 1;
 
    return sum;
}
 
// Driver Code
 
    let n = 4;
 
    document.write(specialSum(n) + "<br>");
 
// This code is contributed by Mayank Tyagi
 
</script>


Output: 

17.0

 

Time Complexity: O(log2(N)) 
Auxiliary Space: O(1),  since no extra space has been taken.
 

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Nango Kalahttps://www.kala.co.za
Experienced Support Engineer with a demonstrated history of working in the information technology and services industry. Skilled in Microsoft Excel, Customer Service, Microsoft Word, Technical Support, and Microsoft Office. Strong information technology professional with a Microsoft Certificate Solutions Expert (Privet Cloud) focused in Information Technology from Broadband Collage Of Technology.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments