Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package problems;
- /*
- Problem 12
- 08 March 2002
- The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
- 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
- Let us list the factors of the first seven triangle numbers:
- 1: 1
- 3: 1,3
- 6: 1,2,3,6
- 10: 1,2,5,10
- 15: 1,3,5,15
- 21: 1,3,7,21
- 28: 1,2,4,7,14,28
- We can see that 28 is the first triangle number to have over five divisors.
- What is the value of the first triangle number to have over five hundred divisors?
- Answer:
- FIVE HUNDRED DIVISORS?
- This means the number has to be made up of at least 500 numbers, and probably a lot more.
- Generate numbers until you find one with 500 divisors?...
- 0.5 x n(n+1)
- */
- public class Problem_12 {
- public static void main(String[] args) {
- int number = 0;
- int i = 1;
- while(numberOfDivisors(number) < 500){
- number += i;
- i++;
- }
- System.out.println("The answer is: " +number +" with " + numberOfDivisors(number) +" factors.");
- } //End of main.
- private static int numberOfDivisors(int inputNumber){
- int nod = 0; // Counts Number Of Divsions
- int sqrt = (int) Math.sqrt(inputNumber);
- /* No need to check higher than the sqrt of the current number,
- because if a value higher than the square root were a factor, it
- would already have been checked. A factor of a number will always
- have a "sibling" so to speak. */
- for(int i = 1; i<= sqrt; i++){
- if(inputNumber % i == 0){
- nod += 2;
- /* You've found one factor, that means there must be
- * another number which is a factor. So you increment
- * by two.
- *
- * ALL numbers have at least two factors (except 1),
- * 1 and the number itself.
- */
- }
- }
- /* Correction if the number is a perfect square.
- * */
- if (sqrt * sqrt == inputNumber) {
- nod--;
- /* In other words, if the factor is the sqrt
- * of the number it has no "sibling number" it
- * is forever alone.
- *
- * Example = 9 has the factors 1, 3 and 9.
- */
- }
- return nod;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement