Hi ya folks, I''v come to this forums a few times and have found solutions to my problems, however in this instance I can not find a solution to my problem.
Here is what I have to do:
The problem is that if the answer is false I run in to a Stack Over Flow error. For example, if the input is 23, I run in to an error, however if the input is 81 it passes (returns true correctly).Write a Boolean recursive method called powerof3 that takes a single positive integer argument and returns true iff the integer is a perfect power of 3 such as 1, 3, 9, 27, 81, ...
For example:
if (powerof3(81))
System.out.println("81 is a power of 3.");
else
System.out.println("81 is not a power of 3.";
displays 81 is a power of 3
Here is my code:
public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here int num = 243; boolean it3 = powerOfThree1(num); System.out.println(it3); } private static boolean powerOfThree1(int num) { boolean n = false; if (num == 1) { n = true; return true; } if (num != 1) { n= powerOfThree1(num / 3); } return n; } }
Can any one tell me how I should go about solving this? Also, is there any other method that I can use?
One more thing: I can not use Arrays, ArrayLists,etc for this assignment.
PS: I'm more of a hardware guy (modder, OCer,etc) than a programmer and I am finding recursions to be a bit difficult to understand and follow. Any tutorials, guides,etc will be helpful.