Project Euler > Problem 89 > Roman numerals (Java Solution)


The rules for writing Roman numerals allow for many ways of writing each number (see About Roman Numerals...). However, there is always a "best" way of writing a particular number.

For example, the following represent all of the legitimate ways of writing the number sixteen:


The last example being considered the most efficient, as it uses the least number of numerals.

The 11K text file, roman.txt (right click and 'Save Link/Target As...'), contains one thousand numbers written in valid, but not necessarily minimal, Roman numerals; that is, they are arranged in descending units and obey the subtractive pair rule (see About Roman Numerals... for the definitive rules for this problem).

Find the number of characters saved by writing each of these in their minimal form.

Note: You can assume that all the Roman numerals in the file contain no more than four consecutive identical units.



The solution may include methods that will be found here: .

public interface EulerSolution{

public String run();

* Solution to Project Euler problem 39
* By Nayuki Minase

public final class p039 implements EulerSolution {

public static void main(String[] args) {
System.out.println(new p039().run());

public String run() {
int maxPerimeter = 0;
int maxTriangles = 0;
for (int p = 1; p <= 1000; p++) {
int triangles = countSolutions(p);
if (triangles > maxTriangles) {
maxTriangles = triangles;
maxPerimeter = p;
return Integer.toString(maxPerimeter);

private static int countSolutions(int p) {
int count = 0;
for (int a = 1; a <= p; a++) {
for (int b = a; b <= p; b++) {
int c = p - a - b;
if (b <= c && a * a + b * b == c * c)
return count;


1 comment :

Follow Me

If you like our content, feel free to follow me to stay updated.


Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?


Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact