java-判斷一個自然數是否是某個數的平方。當然不能使用開方運算
阿新 • • 發佈:2018-12-26
/** * 題目:判斷一個自然數是否是某個數的平方。當然不能使用開方運算 * 方法1.squareRoot0 二分查詢 * 方法2.squareRoot1 * 考慮等差數列 1 3 5 7 9...發現 * 1^2=1 * 2^2=1+3 * 3^2=1+3+5 * ... * 因此,N-1-3-5...若剛好可減至0,則N是某正整數的平方 */ public class TestN { public static void main(String[] args) { for(int i=0;i<100;i++){ squareRootOf(i); } } public static void squareRootOf(int n){ if(n<1){ return; } int x0=squareRoot0(n); if(x0!=-1){ System.out.printf("%d*%d=%d%n", x0,x0,n); } int x1=squareRoot1(n); if(x1!=-1){ System.out.printf("%d*%d=%d%n", x1,x1,n); } } //return sqrt(n).Use binary search public static int squareRoot0(int n){ int low=1; int high=n; while(low<=high){ int mid=(low&high)+(high^low)/2; if(mid*mid==n){//mid*mid,overflow? I don't know how to avoid this. return mid; }else if(mid*mid<n){ low=mid+1; }else{ high=mid-1; } } return -1; } //return sqrt(n). public static int squareRoot1(int n){ int d=1;//d=1,3,5... int count=0; while(n>0){ n-=d; d+=2; count++; if(n==0){ return count; } } return -1; } }