In: Computer Science
Java program to print all the powers of 2 below a certain number. Calculate sum, accept upper limit and make sure sum variable is long type.
Run-
Enter the upper limit: 100
5 + 8 + 9 + 11 + 20 + 32 + 30 = 115
import java.util.Scanner;
public class SumSqure {
public static void main(String[] args) {
Scanner sc = new
Scanner(System.in);
System.out.println("Enter upper
limit: ");
int upper=sc.nextInt();
long temp,sum=0;
//iterating untill the upper
limit
for(int i=0;;i++){
//generate
powers of 2
temp=(long)Math.pow(2, i);
//checking if
generated power is in range
if(temp<=upper){
System.out.print(temp+" ");
sum+=temp;
}
else{
break;
}
}
System.out.println(" =
"+sum);
}
}
The given sample output looks wrong