Addition Challenge: Charlie set off with great zeal to the “Kracker Jack Fun Fair 2017”. There were numerous activities in the fair, though Charlie being a Math expert, liked to participate in the Addition Challenge.
The Challenge given to him was to find S, where S=20 +21+22+………..+2N. He would succeed in his challenge if he manages to tell the answer for the problem before others. He requests your help to solve the problem in a flash.
Help Charlie to find S and win over the challenge.
Hence create a class named AdditionChallenge with the following method.
Method Name | Description |
int findSum(int) | This method should return S. |
Create a driver class called Main. In the Main method, obtain input from the user in the console and display S by calling the findSum method present in the AdditionChallenge class.
[Note: Strictly adhere to the Object Oriented Specifications given in the problem statement.
All class names, attribute names and method names should be the same as specified in the problem statement. Create separate classes in separate files.]
Input Format:
First line of the input contains one integer N (1 ≤ N ≤ 10000).
Output Format:
Output S in a single line.
Refer sample input and output for formatting specifications.
Sample Input 1:
1
Sample Output 1:
3
Sample Input 2:
8
Sample Output 2:
511
Solution
import java.util.*;
class Main{
public static int findSum(int n)
{
int sum = 0;
for(int i=0;i<=n;i++)
{
sum = sum + (1 << i);
}
return sum;
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
//sauravhathi
int result = findSum(n);
System.out.println(result);
}
}
#include <iostream>
using namespace std;
int findSum(int n)
{
int sum = 0;
//sauravhathi
for (int i = 1; i <= n; ++i)
{
sum += 2^i;
}
return sum;
}
int main()
{
int n;
cin >> n;
cout << findSum(n) << endl;
return 0;
}
def findSum(n):
sum = 0
for i in range(0, n + 1):
sum += 2**i
# sauravhathi
return sum
n = int(input())
print(findSum(n))
Happy Learning – If you require any further information, feel free to contact me.