Skip to content

Instantly share code, notes, and snippets.

@Robotto
Last active August 29, 2015 14:10
Show Gist options
  • Save Robotto/4d70ede3e55ab34aa7cf to your computer and use it in GitHub Desktop.
Save Robotto/4d70ede3e55ab34aa7cf to your computer and use it in GitHub Desktop.
Recursive function too calculate the n'th power of x - Run with: "java Power x n" <- where x and n are non-negative integers.
class Power{
public static void main(String[] args)
{
Power runner = new Power();
int x = Integer.parseInt(args[0]);
int n = Integer.parseInt(args[1]);
System.out.println(runner.F(x,n));
}
public int F(int x, int n)
{
if(n==0) return 1;
if(n==1) return x;
if(x%2!=0) return x*F(x,n-1); //if x can't even
else return x^(n/2)^2*F(x,n/2);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment