How to calculate 2 ^ n and (2 ^ n) +1 in java?

2

I'm doing a job where I have to do some calculations with batteries and I need to do tests for two powers and two powers plus two, ie 1, 2, 3, 5, 8, 9, 16, 17 , etc.

The power part of two is done easily, but how do I loop or cycle the powers of two plus one?

    
asked by anonymous 13.04.2017 / 14:53

1 answer

1

It's simple, just do the power calculation and then add 1.

As no more details follow below. The code calculates all powers of 2 and powers of 2 with 1.

Scanner input = new Scanner(System.in);
System.out.print("Digite um número: ");
int numeroEscolhido = input.nextInt(); //número digitado pelo usuário

for(int i = 0; i <= numeroEscolhido; i++){
    int potenciaDe2 = (int)Math.pow(2, i);
    int potenciaDe2Mais1 = (int)Math.pow(2, i) + 1;

    System.out.println(String.format("(2^%s): %s | (2^%s)+1: %s", i, potenciaDe2, i, potenciaDe2Mais1));
}

Entering the number 5 , the output will be:

(2^0): 1 | (2^0)+1: 2  
(2^1): 2 | (2^1)+1: 3  
(2^2): 4 | (2^2)+1: 5  
(2^3): 8 | (2^3)+1: 9  
(2^4): 16 | (2^4)+1: 17  
(2^5): 32 | (2^5)+1: 33

See working on repl.it.

    
13.04.2017 / 15:01