勾股弦數

編寫程序求500 以內的勾股弦數,即滿足 c2=b2+a2的3個數,要求b>a。將所有符合要求的組合存入文本文件中,每個組合佔一行。

package hj;
import java.io.*;
public class Ch01 {
	public static void main(String args[]) {
	 B b = new B();	
	 b.BB();	
	 }
} 
class B{	
	void BB()
	{		
		int a,b,c;		
		int n = 500;		
		File BB = new File("BB.txt");		
		try {		
			FileWriter out = new FileWriter(BB);		
			String line = System.getProperty("line.separator");		
			String result1 = "";		
			String result = "";		
			for(c = 0; c < n; c++) {			
				for(b = 0; b < c; b++) {				
					for(a = 0; a < b; a++) {					
						if(c*c == b*b + a*a) {						
							result = result1 + c + " " + b + " " + a;
				   	System.out.println("a="+a+"\tb="+b+"\tc="+c);
							out.write(result);						
							out.write(line);//該語句實現換行						
							result = "";					
							}				
						}			
					}		
				}		
			out.close();	
			}		
		catch(IOException e) 
		{			
			System.out.println("Error"+e);		
			}	
		}
}

運行結果如下:

勾股

 

 

 

文本文件,請在自己設置的包的目錄下找。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章