Created
October 11, 2017 17:22
-
-
Save javamultiplex/04daa1c6e4871615d82b7dce31125d29 to your computer and use it in GitHub Desktop.
Project Euler Problem 12 - Highly divisible triangular number in Java?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.javamultiplex.projecteuler; | |
import java.util.ArrayList; | |
import java.util.List; | |
/** | |
* | |
* @author Rohit Agarwal | |
* @category Project Euler Problems | |
* @Problem 12 - Highly divisible triangular number. | |
* | |
*/ | |
public class Problem12 { | |
public static void main(String[] args) { | |
int target = 500; | |
long number = 1; | |
long triangularNumber = 0; | |
int count = 0; | |
while (true) { | |
/* | |
* Step 1: Find the triangular number. | |
* | |
* As triangular number is generated by adding natural numbers so | |
* Sum of first n natural number is = n(n+1)/2 | |
* | |
*/ | |
triangularNumber = (number) * (number + 1) / 2; | |
// Step 2: Get the number of divisors. | |
count = getCountofDivisors(triangularNumber); | |
// Step 3: If number of divisors > 500 then print it otherwise | |
// continue. | |
if (count > target) { | |
System.out.println("The value of the first triangle number to have over five hundred divisors :" + triangularNumber); | |
break; | |
} | |
number++; | |
} | |
} | |
private static int getCountofDivisors(long triangularNumber) { | |
long limit = (long) Math.sqrt(triangularNumber); | |
List<Long> list = new ArrayList<>(); | |
long temp = 0; | |
for (long i = 1; i <= limit; i++) { | |
if (triangularNumber % i == 0) { | |
list.add(i); | |
temp = triangularNumber / i; | |
if (i != temp) { | |
list.add(temp); | |
} | |
} | |
} | |
int divisors = list.size(); | |
return divisors; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment