【程式13】 題目:一個整數,它加上100後是一個完全平方數,再加上168 又是一個完全平方數,請問該數是多少?
阿新 • • 發佈:2019-01-28
/* 2017年3月6日15:19:01 java基礎50道經典練習題 例13 Athor: ZJY Purpose: 【程式13】 題目:一個整數,它加上100後是一個完全平方數,再加上168 又是一個完全平方數,請問該數是多少? 程式分析:在10萬以內判斷,先將該數加上100後再開方,再將 該數加上268後再開方,如果開方後的結果滿足如下條件,即是結果。 */ public class ProgramNo13_1 { public static void main(String[] args) { System.out.print("100000以內滿足條件的數有: "); for (int i=0; i<100001; i++) { if(isCompleteSqr(i+100)&&isCompleteSqr(i+268)) { System.out.print(i + " "); } } } private static boolean isCompleteSqr(int number) { boolean complete = false; for (int i=1; i<Math.sqrt(number)+1; i++) { if(number == Math.pow(i, 2)) { complete = true; break; } } return complete; } }
/* 2017年3月6日15:19:01 java基礎50道經典練習題 例13 Athor: ZJY Purpose: */ public class ProgramNo13_2 { public static void main(String[] args){ int n=0; for(int i=0;i<100001;i++){ if(isCompSqrt(i+100) && isCompSqrt(i+268)){ n = i; break; } } System.out.println("所求的數是:"+n); } //判斷完全平方數 private static boolean isCompSqrt(int n){ boolean isComp = false; for(int i=1; i<Math.sqrt(n)+1; i++){ if(n == Math.pow(i,2)){ isComp = true; break; } } return isComp; } }