Confusion with a while statement evaluating if a number is triangular

Posted by Darkkurama on Stack Overflow See other posts from Stack Overflow or by Darkkurama
Published on 2011-11-14T17:38:39Z Indexed on 2011/11/14 17:50 UTC
Read the original article Hit count: 196

Filed under:
|

I've been having troubles trying to figure out how to solve a function. I've been assigned the development of a little programme which tells if a number is "triangular" (a number is triangular when the addition of certain consecutive numbers in the [1,n] interval is n. Following the definition, the number 10 is triangular, because in the [1,10] interval, 1+2+3+4=10).

I've coded this so far:

class TriangularNumber{

  boolean numTriangular(int n) {
    boolean triangular = false;
    int i = n;
    while(n>=0 && triangular){
    //UE06 is a class which contains the function "f0", which makes the addition of all the numbers in a determined interval
    UE06 p = new UE06();
      if ((p.f0(1, i))==n)
        triangular = true;
      else
        i=i-1;
    }
    return triangular;
  }

boolean testTriangular = numTriangular(10) == true && 
  numTriangular(7) == false && 
  numTriangular(6) == true;

  public static void main(String[] args){

    TriangularNumber p = new TriangularNumber();
    System.out.println("testTriangular = " + p.testTriangular);
   } 
}

According to those boolean tests I made, the function is wrong. As I see the function, it goes like this:

  1. I state that the input number in the initial state isn't triangular (triangular=false) and i=n (determining the interval [1,i] where the function is going to be evaluated
  2. While n is greater or equals 0 and the number isn't triangular, the loop starts
  3. The loop goes like this: if the addition of all the numbers in the [1,i] interval is n, the number is triangular, causing the loop to end. If that statement is false, i goes from i to (i-1), starting the loop again with that particular interval, and so on till the addition is n.

I can't spot the error in my "algorithm", any advice?

Thanks!

© Stack Overflow or respective owner

Related posts about java

Related posts about homework