检查BigInteger是不是一个完美的正方形

编程入门 行业动态 更新时间:2024-10-09 16:29:46
本文介绍了检查BigInteger是不是一个完美的正方形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个BigInteger值,假设它是282并且在变量x中。我现在想写一个while循环,声明:

I have a BigInteger value, let's say it is 282 and is inside the variable x. I now want to write a while loop that states:

while b2 isn't a perfect square: a ← a + 1 b2 ← a*a - N endwhile

我将如何使用BigInteger做这样的事情?

How would I do such a thing using BigInteger?

编辑:这样做的目的是为了写一个此方法。正如文章所述,必须检查b2是否不是正方形。

The purpose for this is so I can write this method. As the article states one must check if b2 is not square.

推荐答案

计算整数平方根,然后检查它的正方形是你的号码。这是我使用 Heron方法计算平方根的方法:

Compute the integer square root, then check that its square is your number. Here is my method of computing the square root using Heron's method:

private static final BigInteger TWO = BigInteger.valueOf(2); /** * Computes the integer square root of a number. * * @param n The number. * * @return The integer square root, i.e. the largest number whose square * doesn't exceed n. */ public static BigInteger sqrt(BigInteger n) { if (n.signum() >= 0) { final int bitLength = n.bitLength(); BigInteger root = BigInteger.ONE.shiftLeft(bitLength / 2); while (!isSqrt(n, root)) { root = root.add(n.divide(root)).divide(TWO); } return root; } else { throw new ArithmeticException("square root of negative number"); } } private static boolean isSqrt(BigInteger n, BigInteger root) { final BigInteger lowerBound = root.pow(2); final BigInteger upperBound = root.add(BigInteger.ONE).pow(2); return lowerBoundpareTo(n) <= 0 && npareTo(upperBound) < 0; }

更多推荐

检查BigInteger是不是一个完美的正方形

本文发布于:2023-11-29 06:17:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1645581.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:正方形   完美   BigInteger

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!