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

Asked

Viewed 2,649 times

2

I am doing a work in which I have to do some calculations with batteries and I need to do tests for powers of two and powers of two plus one, namely 1, 2, 3, 5, 8, 9, 16, 17, etc.

The power of two is easily done, but as I make a loop or a cycle for the power of two plus one?

  • You have to do up to what power?

  • @jbueno the power is up to what you want. I am basically making a method in which the user enters the value of the maximum power that wants the tests. For example, if the user puts 5, the tests will be done up to (2 5)+1, ie will do tests at 1,2,3,4,5,8,9,16,17,32,33

  • @jbueno was just that, thanks

1 answer

1


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

As there are more details below. The code calculates all the powers of 2 and the powers of 2 added 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);

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

Entering with the number 5, the exit 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.