2

I am attempting to create a program which finds values which are both "triangle numbers" and "star numbers". However I am slightly confused about when the program branches to the second function etc. Any help is appreciated!

public class Recursion {

        public static void main(String[] args) {
                // TODO Auto-generated method stub
                int count =0;
                int n = 1;
                int t=0;
                int triangularNumber =0;
                while (n<Integer.MAX_VALUE)
                {
                        t = isTriangularNumber(n,count,triangularNumber);  
                        triangularNumber=0;
                        int starNumber= ((6*n)*(n-1)) + 1;
                        if (starNumber ==t)
                        {
                                System.out.println(t);
                        }
                        n++;
                }      
                if (n==Integer.MAX_VALUE)
                {
                    System.exit(0);
                }
        }


        public static int isTriangularNumber(int n, int count, int triangularNumber)
        {
                triangularNumber =triangularNumber + (n-(n-count));
                if (count<=n)
                {      
                        return isTriangularNumber(n,(count++), triangularNumber);
                }      
                else return triangularNumber;
        }

}

1 Answer 1

4
return isTriangularNumber(n,(count++), triangularNumber);

In the above invocation, count++ is evaluated to count only. So, on every invocation, you are actually passing unchanged value of count. And hence the if condition: -

if (count<=n)

will always be evaluated to true, if it is true for the first invocation. Thus filling the stack with infinite method invocation.

Your invocation should be with ++count: -

return isTriangularNumber(n,(++count), triangularNumber);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.