# Problem with Recursive code

• February 21st, 2010, 07:00 PM
[SOLVED]Problem with Recursive code
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:
Quote:

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
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).

Here is my code:
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.
• February 21st, 2010, 07:17 PM
Freaky Chris
Re: Problem with Recursive code
Check to see if num is below 1, if it is then you know that your number is not a power of 3. Also, by my judgement your program will consider 82 to be a power of 3, which as you well know is 1 more than 81 which is a power of three so 82 cannot be a power of three. You may wish to sort this out. I'll give you a massive clue

82/3 != 27

Regards,
Chris
• February 21st, 2010, 08:22 PM