Multiply by the power of 2 in java?

Soldato
Joined
27 Aug 2004
Posts
17,111
Location
Geordieland
I need to multiply by the power of 1^2, 2^2, 3^3 etc etc

Im crap at maths, is it possible for anyone to tell me how to code this in java pretty please?

Cheers
 
Hmmm, think ive jsut found a solution.

Quick Q, is 2*=2 the equivalent of 2^2? Ive just tried it and it works.
 
Stellios said:
Hmmm, think ive jsut found a solution.

Quick Q, is 2*=2 the equivalent of 2^2? Ive just tried it and it works.

I'm not entirely sure what it is in java, although it might be a function such as pow() or it could even actually be 2^2 (^ is the power operator in C#, might be the same in Java).

However, just to correct you on your above question, 2*=2 is equivalent to 2 = 2 * 2 (or a = a * b). It just so happens that in your example 2*=2 and 2 raised to the power of 2 produce the same answer.
 
2^0 = 1
2^1 = 2 = 2
2^2 = 2*2 = 4
2^3 = 2*2*2 = 8
2^4 = 2*2*2*2 = 16

Etc.

You can either do it recursively (using the base case as 2^0 = 1) - probably not as good performance wise (but it looks neat in programming terms), or use an iterative method.

elkdanger said:
I'm not entirely sure what it is in java, although it might be a function such as pow() or it could even actually be 2^2 (^ is the power operator in C#, might be the same in Java).

Using that might be quite a bit slower.
dunno.gif
 
Stellios said:
I need to multiply by the power of 1^2, 2^2, 3^3 etc etc

If you're just squaring something (x^2) then you multiply it by itself. (x * x)

If you're cubing something (x^3), then you multiply it by itself twice (x * x * x)

:)
 
Back
Top Bottom