java-判断一个自然数是否是某个数的平方。当然不能使用开方运算

/** 
     * 题目:判断一个自然数是否是某个数的平方。当然不能使用开方运算 
     * 方法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;  
	    }  
	}  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值