Help with GCD

I am trying to write a method for a recursive method with the method signature as:

publicint gcdRec(int num1,int num2)

this is what i have written:

publicclass GCD

{

publicint gcdRec(int num1,int num2)

{

if (num2 == 0)

return num1;

else

return gcdRec(num2, num1%num2);

}

}

class Test//class to test the method

{

publicstaticvoid main(String [] args)

{

int x = 5;

int y = 10;

System.out.println("The GCD of" + x +"and" + y +"is" + GCD.gcdRec(x,y));

}

}

After compliation, i encounter this error: non-static method gcdRec(int,int) cannot be referenced from a static context. How do i change the class to test the method? Secondly, is my recursive mehtod gcdRec correct? Pls guide.

[1806 byte] By [Pokemona] at [2007-11-26 23:44:52]
# 1

Either make the method gcdRec(...) static or create an intance of GCD inside your main method and call it like this:instanceOfGCD.gcdRec(x,y)

> Secondly, is my recursive mehtod gcdRec correct?

> Pls guide.

That can be answered by "trial and error"!

; )

Good luck.

prometheuzza at 2007-7-11 15:16:40 > top of Java-index,Java Essentials,New To Java...
# 2
I dun understand what is mean by making an instance of the method inside the main method. Pls elaborate more.
Pokemona at 2007-7-11 15:16:40 > top of Java-index,Java Essentials,New To Java...
# 3
You create an instance of a class using the new operator.Object o = new Object();Once you have an instance, you can call methods within that class.o.method();
floundera at 2007-7-11 15:16:40 > top of Java-index,Java Essentials,New To Java...