Connecting Tech Pros Worldwide Forums | Help | Site Map

implementing x^y

Newbie
 
Join Date: Sep 2009
Posts: 22
#1: 3 Weeks Ago
hi all,

how can i implement x^y in java?

Expand|Select|Wrap|Line Numbers
  1.     public static void main(String[] args) {
  2.         // TODO Auto-generated method stub
  3.         int a = 2;
  4.         int c =0;
  5.        c= a^2;
  6.        System.out.println(c);    
  7.  
  8.     }
  9.  
i get the output c = 0 but it should be 4

thanks

Lives Here
 
Join Date: Sep 2006
Posts: 12,070
#2: 3 Weeks Ago

re: implementing x^y


Read the API specs for the methods in the java.lang.Math class.
Newbie
 
Join Date: Nov 2007
Posts: 31
#3: 3 Weeks Ago

re: implementing x^y


If you are working with nonnegative integers and you want to actually implement this your self (as a homework or whatever), use a for loop.

Perhaps the section on Effectively Computing a Power in the Wikipedia article on exponentiation may help. It takes a little implementing but it's a nice algorithm.
Reply