Skip to content

Commit 7536ef4

Browse files
Merge pull request TheAlgorithms#1454 from shellhub/master
Created Problem04 in ProjectEuler
2 parents 3fb71bc + c0c8305 commit 7536ef4

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

DIRECTORY.md

+1
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,7 @@
203203
## ProjectEuler
204204
* [Problem01](https://github.com/TheAlgorithms/Java/blob/master/ProjectEuler/Problem01.java)
205205
* [Problem02](https://github.com/TheAlgorithms/Java/blob/master/ProjectEuler/Problem02.java)
206+
* [Problem04](https://github.com/TheAlgorithms/Java/blob/master/ProjectEuler/Problem04.java)
206207

207208
## Searches
208209
* [BinarySearch](https://github.com/TheAlgorithms/Java/blob/master/Searches/BinarySearch.java)

ProjectEuler/Problem04.java

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package ProjectEuler;
2+
3+
/**
4+
* A palindromic number reads the same both ways.
5+
* The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
6+
* <p>
7+
* Find the largest palindrome made from the product of two 3-digit numbers.
8+
* <p>
9+
* link: https://projecteuler.net/problem=4
10+
*/
11+
public class Problem04 {
12+
public static void main(String[] args) {
13+
14+
assert solution1(10000) == -1;
15+
assert solution1(20000) == 19591; /* 19591 == 143*137 */
16+
assert solution1(30000) == 29992; /* 29992 == 184*163 */
17+
assert solution1(40000) == 39893; /* 39893 == 287*139 */
18+
assert solution1(50000) == 49894; /* 49894 == 494*101 */
19+
assert solution1(60000) == 59995; /* 59995 == 355*169 */
20+
assert solution1(70000) == 69996; /* 69996 == 614*114 */
21+
assert solution1(80000) == 79897; /* 79897 == 733*109 */
22+
assert solution1(90000) == 89798; /* 89798 == 761*118 */
23+
assert solution1(100000) == 99999; /* 100000 == 813*123 */
24+
}
25+
26+
private static int solution1(int n) {
27+
for (int i = n - 1; i >= 10000; --i) {
28+
String strNumber = String.valueOf(i);
29+
30+
/* Test if strNumber is palindrome */
31+
if (new StringBuilder(strNumber).reverse().toString().equals(strNumber)) {
32+
for (int divisor = 999; divisor >= 100; --divisor) {
33+
if (i % divisor == 0 && String.valueOf(i / divisor).length() == 3) {
34+
return i;
35+
}
36+
}
37+
}
38+
}
39+
return -1; /* not found */
40+
}
41+
}

0 commit comments

Comments
 (0)