James
James

Reputation: 469

Why does my program not work as expected?

I am working on problem twelve on project Euler. It is all about triangle numbers; I am trying to find the first triangle number with more than 500 divisors. I have written a program to find this, however, it is not giving me the correct answer and I can not see why. I have provided my code below:

public class problemTwelve {
  public static void main(String [] args) {
    int i = 1;
    int number = 1;
   while(getDivisors(number) < 500) {
     number += i;
     i++;
   }
   System.out.println("The first triangle number to have greater than 500 divisors is: " + number);
  }

  private static int getDivisors(int triangleNum) {
    int noOfDivisors = 0;
    int numToTest = (int) Math.sqrt(triangleNum);
    for(int i = 1; i <= numToTest; i++) {
      if((triangleNum % i) == 0) {
        noOfDivisors += 2;
      }
    }
    if((numToTest * numToTest) == triangleNum) {
      noOfDivisors--;
    }
    return noOfDivisors;
  }
}

The output given by the program upon running it is as follows:

The first triangle number to have greater than 500 divisors is: 146611080

Upon entering this number as the answer on project Euler, we can see that it is wrong. I don't know where I have gone wrong in my program...

Upvotes: 1

Views: 59

Answers (2)

Arian
Arian

Reputation: 103

you have to start your numbers from 0 not 1 , here is the correct code :

int i = 1;
    int number = 0;
    while(getDivisors(number) < 500) {
        number += i;
        i++;
    }
    System.out.println("The first triangle number to have greater than 500 divisors is: " + number);
}


private static int getDivisors(int triangleNum) {
    int noOfDivisors = 0;
    int numToTest = (int) Math.sqrt(triangleNum);
    for(int i = 1; i <= numToTest; i++) {
        if(triangleNum % i == 0) {
            noOfDivisors += 2;
        }
    }
    if((numToTest * numToTest) == triangleNum) {
        noOfDivisors--;
    }
    return noOfDivisors;
}

Upvotes: 0

Bastien Aracil
Bastien Aracil

Reputation: 1821

It seems that the number you are checking are not triangle. Just at looking at the code, the second number checked is 2 which is not a triangle number.

Try moving the line

i++;
before the line
number+=i;

Upvotes: 1

Related Questions