ProjectEuler - 9

问题:

A Pythagorean triplet is a set of three natural numbers, a < b <c, for which,

a 2 + b 2 = c 2

For example, 32 + 42 = 9 + 16 = 25 = 52.

There exists exactly one Pythagorean triplet for which a + b +c = 1000.
Find the product abc.

翻译:

毕氏三元數组是这样3个数字组合,a2 + b2 = c2 且 a<b<c; 找到一个毕氏三元數组,且使其和为1000。


代码:

方法一:

public static long getResult1() {
		long result = 1;
		for (int c = 1; c < N; c++) {
			for (int b = 1; b < N; b++) {
				for (int a = 1; a < N; a++) {
					if (a < b && b < c) {
						if (1000 == a + b + c) {
							if (a * a + b * b == c * c) {
								System.out.printf("a=%d,b=%d,c=%d\n", a, b, c);
								result = a * b * c;
							}
						}
					}
				}
			}
		}
		return result;
	}


方法二  (条件中有a<b<c的条件,所以b起始为a,c起始为b,可以省去一部分浪费时间):

public static long getResult2() {
		int result = 1;
		for (int a = 1; a < N; a++) {
			for (int b = a; b < N; b++) {
				for (int c = b; c < N; c++) {
					if (1000 == a + b + c) {
						if (a * a + b * b == c * c) {
							System.out.printf("a=%d,b=%d,c=%d\n", a, b, c);
							result = a * b * c;
						}
					}
				}
			}
		}
		return result;
	}

方法三  (利用条件 a<b<c 且 a+b+c=1000, 说明如果c<1000/3的话,是不可能到达的。 所以c的起始点应该还可以增加判断 c = (b?N/3 ? b:N/3),选择其中大的一个。

public static long getResult3() {
		int result = 1;
		for (int a = 1; a < N; a++) {
			for (int b = a; b < N; b++) {
				for (int c = (b>N/3?b:N/3); c < N; c++) {
					if (1000 == a + b + c) {
						if (a * a + b * b == c * c) {
							System.out.printf("a=%d,b=%d,c=%d\n", a, b, c);
							result = a * b * c;
						}
					}
				}
			}
		}
		return result;
	}

自己测试了一下三个方法所用的时间:
a=200,b=375,c=425
getResult1:642
a=200,b=375,c=425
getResult2:121
a=200,b=375,c=425
getResult3:118

public static void main(String[] args) {
		long startTime;
		long endTime;
		startTime = System.currentTimeMillis();
		getResult1();
		endTime = System.currentTimeMillis();
		System.out.println("getResult1:"+(endTime-startTime));
		
		startTime = System.currentTimeMillis();
		getResult2();
		endTime = System.currentTimeMillis();
		System.out.println("getResult2:"+(endTime-startTime));
		
		startTime = System.currentTimeMillis();
		getResult3();
		endTime = System.currentTimeMillis();
		System.out.println("getResult3:"+(endTime-startTime));
	}




你可能感兴趣的:(算法,欧拉项目)