kanetaiの二次記憶装置

プログラミングに関するやってみた、調べた系のものをQitaに移して、それ以外をはてブでやる運用にしようと思います。http://qiita.com/kanetai

Is it a Right Triangle(AOJ No.0003), Simultaneous Equation(AOJ No.0004)

リポジトリ

Is it a Right Triangle?(AOJ No.0003)

3辺の長さが与えられたとき直角三角形(right triangle)になっているかどうかを判定する

アルゴリズム

 a^2 = b^2 + c^2が成り立つか調べる
 a>bかつa>c

コード

はじめ、right triangleを"正しい三角形"と読んで、三角不等式が成り立つか調べてた。
俺バカスwww

import java.util.*;
public class aoj0003 {
	static final Scanner stdin = new Scanner(System.in);
	static final String solve(int a, int b, int c){
		return ( a*a == b*b + c*c || b*b == c*c + a*a || c*c == a*a + b*b ) ? "YES" : "NO";
	}
	public static void main(String[] args) {
		int n = stdin.nextInt();
		while( n-- != 0 ){
			int a = stdin.nextInt();
			int b = stdin.nextInt();
			int c = stdin.nextInt();
			System.out.println( solve(a,b,c) );
		}
	}
}

Simultaneous Equation(AOJ No.0004)

 a,b,c,d,e,fが与えられて、連立方程式
 \left \{ \begin{array}{c} ax + by = c \\ dx + ey = f \end{array} \right.
を解く

アルゴリズム

低次なので解析的に解くだけでおk
●Cramerの公式(Cramer's fomula)
連立1次方程式 {\bf Ax}={\bf b}について、係数行列 {\bf A}=[ {\bf a}_1 , {\bf a}_2 , \cdots , {\bf a}_n ] が正則( |{\bf A}|\neq 0)ならば、ただ一組の解
 \begin{array}{cc} x_i = \frac{|{\bf a}_1 ,\cdots , {\bf a}_{i-1}, {\bf b} , {\bf a}_{i+1}, \cdots ,{\bf a}_n |}{|{\bf A}|} & (1\leq i \leq n) \end{array}
をもつ。
問題のOutputは、小数2つ(x y)なので、必ず解は一意に決まるようなInputだろうから、
正則かどうか考慮する必要はない。

コード

小数点以下3桁で表示せよという指示があるが、そのままだと、
解が0のとき場合によっては-0.000と出力され、wrong answerになってしまう。
+0.0して-がつくのを回避した。

import java.util.*;
public class aoj0004 {
	static final Scanner stdin = new Scanner(System.in);
	public static void main(String[] args) {
		while(stdin.hasNext()){
			double a = stdin.nextDouble();
			double b = stdin.nextDouble();
			double c = stdin.nextDouble();
			double d = stdin.nextDouble();
			double e = stdin.nextDouble();
			double f = stdin.nextDouble();
			double x[] = solve(a,b,c,d,e,f);
			System.out.printf("%.3f %.3f\n", x[0], x[1]);
		}
	}
	static final double[] solve(double a, double b, double c, double d, double e, double f){
		double[] ans = new double[2];
		ans[0] = (c*e - b*f) / (a*e - b*d) + 0.0; //+0.0 が無いと場合によっては
		ans[1] = (a*f - c*d) / (a*e - b*d) + 0.0; //printfしたとき -0.000と出てwrong answerになってしまう
		return ans;
	}
}