• Post Reply Bookmark Topic Watch Topic
  • New Topic

Problems calculating 2^n with For loop  RSS feed

 
Silke Sewell
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to calculate 2^n with a for loop and am having some difficulties. My program uses a loop to generate numbers 1-20 which are then used to be n.
So if n = 3 (2^3) it should calculate 2*2*2, if n = 5 (2^5) it should calculate 2*2*2*2*2. But it does not do that, not sure what it does. It's the method all the way on the bottom that is giving me a hard time. Can someone help?

 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Silke Sewell wrote:...not sure what it does. It's the method all the way on the bottom...

Welcome to the ranch!

To see what your method is actually doing, add some println statements. For example...

This should show you where it's going wrong.
 
Antany Vasanth
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Silke,

Welcome to Java Ranch

In the exponent method

why have you assigned also verify your loop within exponent which executes n+1 times.

Regards,
Antany.


 
Silke Sewell
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
marc weber wrote:
Silke Sewell wrote:...not sure what it does. It's the method all the way on the bottom...

Welcome to the ranch!

To see what your method is actually doing, add some println statements. For example...

This should show you where it's going wrong.


Thank you I have been trying to figure out a way to debug in JGrasp this helped. I got it fixed.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since these are powers of 2, a nice exercise would be to code this using bit shifting instead of a for loop.
 
salvin francis
Bartender
Posts: 1649
37
Eclipse IDE Google Web Toolkit Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
by the way, this too looks wrong to me:



isnt it same as :



I am not looking at the logic though, its just an observation.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!