Question

In java please. SumOfPowerOfTwo The following program can be done in a single class. Write a...

In java please.

SumOfPowerOfTwo

The following program can be done in a single class.

Write a program that requests and reads in a integer number between 1 and 40 inclusively. Repeat the loop until a proper number is entered.

Call the method powersOfTwoSum with the number as the actual parameter. Expect a value of type long as a return value.

powersOfTwoSum(int number)

This method must use a recursive technique to return the sum of the powers of two from the number down to zero. For example, if the input is 5 the return value would be:

25 + 24 + 23 + 22 + 21 +1

Two Samples:

Enter an integer between 1 and 20 inclusively: 2

The sum of the powers of two from 0 to 2 is 7

Enter an integer between 1 and 40 inclusively: 40

The sum of the powers of two from 0 to 40 is 2199023255551

0 0
Add a comment Improve this question Transcribed image text
Answer #1

The answer to this question is as follows:

The code I provided should work is as follows:

for 2 the output is 7 because 20+21+22=1+2+4=7

for 5 the output is 63 because of 20+21+22+23+24+25=1+2+4+8+16+32=63

import java.util.*;
public class MyClass {
long powersOfTwoSum(int num)
{
int sum=(int)(Math.pow(2,num));
if(num==0)
{
return 1;
}
else
return powersOfTwoSum((num-1))+sum;
}
  
public static void main(String args[]) {
int num;
Scanner sc=new Scanner(System.in);
num=sc.nextInt();
while(true)
{
if(num>=1 && num<=40)
{
break;
}
else
{
System.out.println("Enter an integer between 1 and 20 inclusively:");
num=sc.nextInt();
}
}
MyClass m=new MyClass();
System.out.println(m.powersOfTwoSum(num));
}
}

Add a comment
Know the answer?
Add Answer to:
In java please. SumOfPowerOfTwo The following program can be done in a single class. Write a...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT