本文主要是介绍Java大数开方模板及判断一个大数是否是平方数模板,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
判断是否是平方数
public static int judge (BigInteger x)///通过二分在区间(0,x)寻找是否有平方等于n的数{BigInteger left=BigInteger.ZERO,right=x,mid,ans;int sign;while(left.compareTo(right)<=0)///l<=r 注意有带等号{mid=left.add(right).shiftRight(1);//求出中间值mid=(right+left)/2ans=mid.multiply(mid);///ans=mid*midsign=ans.compareTo(x);///比较区间中间值的平方与x的大小if(sign==0) return 1;///相等else if(sign<0) left=mid.add(BigInteger.ONE);///ans小,左端点位mid+1else left=mid.subtract(BigInteger.ONE);///ans大,右端点为mid-1}return 0;}
算出开方数( 参考博客 )
import java.math.BigInteger;
import java.util.Scanner;public class Main {final static BigInteger NUM20 = BigInteger.valueOf(20);// 将后面使用的参数定义为final常量public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.println(kaifang(input.next));}// 手算法开方public static String kaifang(String s) {String result = "0";// 结果初始化为字符串0String remainder = "";// 余数if (s.length() % 2 != 0)// 将字符串长度变为偶数s = "0" + s;for (int i = 0; i < s.length() / 2; i++) {// 两两分组remainder += s.substring(i * 2, (i + 1) * 2);// 余数为之前的结果加上后面2个数字int shang = f1(new BigInteger(remainder), new BigInteger(result));remainder = f2(new BigInteger(remainder), new BigInteger(result), BigInteger.valueOf(shang)) + "";result += shang;}return result.substring(1);// 去掉结果之前的0}// public static int f1(int remainder, int result) {
// int i;
// for (i = 9; i >= 0; i--)
// if ((result * 20 + i) * i <= remainder)
// break;
// return i;
// }
//
// public static int f2(int remainder, int result, int shang) {
// return remainder - (result * 20 + shang) * shang;
// }public static int f1(BigInteger remainder, BigInteger result) {int i;for (i = 9; i >= 0; i--) {BigInteger NUMI = BigInteger.valueOf(i);if (result.multiply(NUM20).add(NUMI).multiply(NUMI).compareTo(remainder) <= 0)break;}return i;}public static String f2(BigInteger remainder, BigInteger result, BigInteger shang) {return remainder.subtract(result.multiply(NUM20).add(shang).multiply(shang)).toString();}
}
这篇关于Java大数开方模板及判断一个大数是否是平方数模板的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!