2008-11-17 13:43:21 8 Comments

I'm looking for the fastest way to determine if a `long`

value is a perfect square (i.e. its square root is another integer):

- I've done it the easy way, by using the built-in
`Math.sqrt()`

function, but I'm wondering if there is a way to do it faster by restricting yourself to integer-only domain. - Maintaining a lookup table is impractical (since there are about
2
^{31.5}integers whose square is less than 2^{63}).

Here is the very simple and straightforward way I'm doing it now:

```
public final static boolean isPerfectSquare(long n)
{
if (n < 0)
return false;
long tst = (long)(Math.sqrt(n) + 0.5);
return tst*tst == n;
}
```

_{Note: I'm using this function in many Project Euler problems. So no one else will ever have to maintain this code. And this kind of micro-optimization could actually make a difference, since part of the challenge is to do every algorithm in less than a minute, and this function will need to be called millions of times in some problems.}

I've tried the different solutions to the problem:

- After exhaustive testing, I found that adding
`0.5`

to the result of Math.sqrt() is not necessary, at least not on my machine. - The fast inverse square root was faster, but it gave incorrect results for n >= 410881. However, as suggested by BobbyShaftoe, we can use the FISR hack for n < 410881.
- Newton's method was a good bit slower than
`Math.sqrt()`

. This is probably because`Math.sqrt()`

uses something similar to Newton's Method, but implemented in the hardware so it's much faster than in Java. Also, Newton's Method still required use of doubles. - A modified Newton's method, which used a few tricks so that only integer math was involved, required some hacks to avoid overflow (I want this function to work with all positive 64-bit signed integers), and it was still slower than
`Math.sqrt()`

. - Binary chop was even slower. This makes sense because the binary chop will on average require 16 passes to find the square root of a 64-bit number.
- According to John's tests, using
`or`

statements is faster in C++ than using a`switch`

, but in Java and C# there appears to be no difference between`or`

and`switch`

. - I also tried making a lookup table (as a private static array of 64 boolean values). Then instead of either switch or
`or`

statement, I would just say`if(lookup[(int)(n&0x3F)]) { test } else return false;`

. To my surprise, this was (just slightly) slower. This is because array bounds are checked in Java.

### Related Questions

#### Sponsored Content

#### 26 Answered Questions

#### 6 Answered Questions

### [SOLVED] Integer cube root

**2010-12-02 04:57:37****Charles****6728**View**17**Score**6**Answer- Tags: c optimization math gcc numerical-analysis

#### 18 Answered Questions

### [SOLVED] What are the effects of exceptions on performance in Java?

**2008-11-18 15:31:11****John Ellinwood****79595**View**496**Score**18**Answer- Tags: java performance exception

#### 34 Answered Questions

### [SOLVED] Fastest way to list all primes below N

**2010-01-14 23:40:27****jbochi****199792**View**357**Score**34**Answer- Tags: python math optimization primes

#### 5 Answered Questions

### [SOLVED] Why is (a*b != 0) faster than (a != 0 && b != 0) in Java?

**2016-02-21 01:51:17****Maljam****21119**View**412**Score**5**Answer- Tags: java performance processing-efficiency microbenchmark branch-prediction

#### 1 Answered Questions

#### 5 Answered Questions

### [SOLVED] Fastest way to determine if an integer is between two integers (inclusive) with known sets of values

**2013-06-13 19:21:42****jjxtra****59447**View**389**Score**5**Answer- Tags: c++ c performance math

#### 8 Answered Questions

### [SOLVED] Fastest way to convert string to integer in PHP

**2008-10-27 05:18:57****nickf****357662**View**251**Score**8**Answer- Tags: php optimization casting

#### 2 Answered Questions

### [SOLVED] Fastest Inverse Square Root on iPhone

**2014-01-10 07:41:34****WolfLink****1034**View**6**Score**2**Answer- Tags: ios objective-c optimization physics neon

#### 12 Answered Questions

### [SOLVED] How can I improve this square root method?

**2009-05-13 05:34:45****David Brown****7523**View**5**Score**12**Answer- Tags: c# algorithm optimization math performance

## 30 comments

## @Sajjad Ali Vayani 2019-11-01 07:53:17

Square Root of a number, given that the number is a perfect square.

The complexity is log(n)

## @Kibbee 2008-11-17 13:51:45

I'm not sure if it would be faster, or even accurate, but you could use John Carmack's Magical Square Root, algorithm to solve the square root faster. You could probably easily test this for all possible 32 bit integers, and validate that you actually got correct results, as it's only an appoximation. However, now that I think about it, using doubles is approximating also, so I'm not sure how that would come into play.

## @jalf 2008-11-17 15:22:49

I believe Carmack's trick is fairly pointless these days. The built-in sqrt instruction is a lot faster than it used to be, so you may be better off just performing a regular square root and testing if the result is an int. As always, benchmark it.

## @luke 2008-11-17 18:45:30

doubles can always represent integers in their range exactly

## @Kip 2008-11-17 19:55:13

This breaks starting at n=410881, the John Carmack magic formula returns 642.00104, when the actual square root is 641.

## @finnw 2010-01-07 11:57:49

I recently used Carmack's trick in a Java game and it was very effective, giving a speedup of about 40%, so it is still useful, at least in Java.

## @Robert Fraser 2010-05-06 10:27:45

@finnw - +40% in actual framerate or just in the sqrt function? I'm actually quite surprised about this, since most of the games I've played (and the one I've made in XNA) have been GPU-bound instead of CPU-bound anyway (though I know this can differ between use's machine, blah blah blah)

## @finnw 2010-05-06 10:48:51

@Robert Fraser Yes +40% in the overall frame rate. The game had a particle physics system which took up nearly all available CPU cycles, dominated by the square root function and the round-to-nearest-integer function (which I had also optimised using a similar bit twiddling hack.)

## @Antimony 2013-08-27 14:28:29

@luke but they can't represent longs above 2^53.

## @maaartinus 2014-05-19 21:07:16

@Antimony Right, but it works when done right, see my solution below.

## @Pixar 2018-06-02 18:45:37

The link is broken.

## @Daniel Gray 2019-07-02 00:38:22

The link has been fixed by pointing it to the Wayback Machine's snapshot from around the time this was posted :)

## @bgiles 2009-03-25 15:23:05

Project Euler is mentioned in the tags and many of the problems in it require checking numbers >>

`2^64`

. Most of the optimizations mentioned above don't work easily when you are working with an 80 byte buffer.I used java BigInteger and a slightly modified version of Newton's method, one that works better with integers. The problem was that exact squares

`n^2`

converged to`(n-1)`

instead of`n`

because`n^2-1 = (n-1)(n+1)`

and the final error was just one step below the final divisor and the algorithm terminated. It was easy to fix by adding one to the original argument before computing the error. (Add two for cube roots, etc.)One nice attribute of this algorithm is that you can immediately tell if the number is a perfect square - the final error (not correction) in Newton's method will be zero. A simple modification also lets you quickly calculate

`floor(sqrt(x))`

instead of the closest integer. This is handy with several Euler problems.## @user2975337 2015-07-14 02:27:31

I was thinking the same thing about these algorithms not translating well to multi-precision buffers. So thought I'd stick this here... I actually found a probabilistic squaredness test with better asymptotic complexity for huge numbers..... where number theory applications not uncommonly find themselves. Not familiar with Project Euler though... looks interesting.

## @Viktor 2019-01-19 13:44:25

May be the best algorithm for the problem is a fast integer square root algorithm https://stackoverflow.com/a/51585204/5191852

There @Kde claims that three iterations of the Newton method would be sufficient for the accuracy of ±1 for 32 bit integers. Certainly, more iterations are needed for 64-bit integers, may be 6 or 7.

## @MWB 2018-12-27 17:13:51

Here is a divide and conquer solution.If the square root of a natural number (

`number`

) is a natural number (`solution`

), you can easily determine a range for`solution`

based on the number of digits of`number`

:`number`

has 1 digit:`solution`

in range = 1 - 4`number`

has 2 digits:`solution`

in range = 3 - 10`number`

has 3 digits:`solution`

in range = 10 - 40`number`

has 4 digits:`solution`

in range = 30 - 100`number`

has 5 digits:`solution`

in range = 100 - 400Notice the repetition?

You can use this range in a binary search approach to see if there is a

`solution`

for which:Here is the codeHere is my class SquareRootChecker

And here is an example on how to use it.

## @Jack Giffin 2020-01-23 21:45:51

I love the concept, but I would like to politely point out a major flaw: numbers are in base 2 binary. Converting base 2 to base 10 via

`toString`

is an incredibly expensive operation compared to bitwise operators. Thus, to satisfy the objective of the question--performance--you must use bitwise operators instead of base 10 strings. Again, I really like your concept. Notwithstanding, your implementation (as it stands now) is by far the slowest out of all the possible solutions posted for the question.## @Albert van der Horst 2018-12-27 02:42:56

Calculating square roots by Newton's method is horrendously fast ... provided that the starting value is reasonable. However there is no reasonable starting value, and in practice we end with bisection and log(2^64) behaviour.

To be really fast we need a fast way to get at a reasonable starting value, and that means we need to descend into machine language. If a processor provides an instruction like POPCNT in the Pentium, that counts the leading zeroes we can use that to have a starting value with half the significant bits. With care we can find a a fixed number of Newton steps that will always suffice. (Thus foregoing the need to loop and have very fast execution.)

A second solution is going via the floating point facility, which may have a fast sqrt calculation (like the i87 coprocessor.) Even an excursion via exp() and log() may be faster than Newton degenerated into a binary search. There is a tricky aspect to this, a processor dependant analysis of what and if refinement afterwards is necessary.

A third solution solves a slightly different problem, but is well worth mentionning because the situation is described in the question. If you want to calculate a great many square roots for numbers that differ slightly, you can use Newton iteration, if you never reinitialise the starting value, but just leave it where the previous calculation left off. I've used this with success in at least one Euler problem.

## @MWB 2018-12-27 17:58:49

Getting a good estimate is not too hard. You can use the number of digits of the number to estimate a lower and upper bound for the solution. See also my answer where I propose a divide and conquer solution.

## @Albert van der Horst 2018-12-29 16:27:09

What is the difference between POPCNT and counting the number of digits? Except that you can do POPCNT in one nanosecond.

## @aventurin 2018-10-17 22:49:54

## Newton's Method with integer arithmetic

If you wish to avoid non-integer operations you could use the method below. It basically uses Newton's Method modified for integer arithmetic.

This implementation can not compete with solutions that use

`Math.sqrt`

. However, its performance can be improved by using the filtering mechanisms described in some of the other posts.## @MWB 2018-09-26 16:32:44

Not sure if this is the fastest way, but this is something I stumbled upon (long time ago in high-school) when I was bored and playing with my calculator during math class. At that time, I was really amazed this was working...

## @Albert van der Horst 2018-12-27 11:57:18

Oops, this is an O(N^.5) algorithm, so it is really bad regards speed, and lasts forever for 63 bit numbers that may be input. I changed my upvode to a downvote. What was I thinking when I upvoted it. At least the idea behind it is correct, but I didn't test it.

## @mrzl 2008-11-18 15:57:44

`Math.sqrt()`

works with doubles as input parameters, so you won't get accurate results for integers bigger than2^53.## @Kip 2009-01-06 14:33:38

I've actually tested the answer on all perfect squares larger than 2^53, as well as all numbers from 5 below each perfect square to 5 above each perfect square, and I get the correct result. (the roundoff error is corrected when I round the sqrt answer to a long, then square that value and compare)

## @maaartinus 2013-09-08 19:12:27

@Kip: I guess I've proven that it works.

## @mwfearnley 2014-04-22 00:54:04

The results aren't perfectly accurate, but more accurate than you might think. If we assume at least 15 accurate digits after the conversion to double and after the square root, then that's plenty, because we need no more than 11: 10 digits for the 32-bit square root and less than 1 for a decimal place, because the +0.5 rounds to nearest.

## @gnasher729 2014-05-01 23:27:49

Math.sqrt() isn't totally accurate, but it doesn't have to. In the very first post, tst is an integer close to sqrt (N). If N is not a square, then tst * tst != N, no matter what the value of tst is. If N is a perfect square, then sqrt (N) < 2^32, and as long as sqrt (N) is calculated with an error < 0.5, we are fine.

## @nabam serbang 2010-12-04 01:22:34

Considering for general bit length (though I have used specific type here), I tried to design simplistic algo as below. Simple and obvious check for 0,1,2 or <0 is required initially. Following is simple in sense that it doesn't try to use any existing maths functions. Most of the operator can be replaced with bit-wise operators. I haven't tested with any bench mark data though. I'm neither expert at maths or computer algorithm design in particular, I would love to see you pointing out problem. I know there is lots of improvement chances there.

## @nabam serbang 2010-12-18 15:06:26

@Kip: Some problem with my browser.

## @Steve Kuo 2011-03-10 03:25:26

You need some indenting.

## @maaartinus 2013-09-08 17:37:37

I'm pretty late to the party, but I hope to provide a better answer; shorter and (assuming my benchmark is correct) also much faster.

The first test catches most non-squares quickly. It uses a 64-item table packed in a long, so there's no array access cost (indirection and bounds checks). For a uniformly random

`long`

, there's a 81.25% probability of ending here.The second test catches all numbers having an odd number of twos in their factorization. The method

`Long.numberOfTrailingZeros`

is very fast as it gets JIT-ed into a single i86 instruction.After dropping the trailing zeros, the third test handles numbers ending with 011, 101, or 111 in binary, which are no perfect squares. It also cares about negative numbers and also handles 0.

The final test falls back to

`double`

arithmetic. As`double`

has only 53 bits mantissa, the conversion from`long`

to`double`

includes rounding for big values. Nonetheless, the test is correct (unless the proof is wrong).Trying to incorporate the mod255 idea wasn't successful.

## @dfeuer 2014-07-11 01:04:04

That implicit masking of the shift value is a bit ... evil. Do you have any idea why that's in the Java spec?

## @dfeuer 2014-07-11 01:08:58

A question about your code in particular: why do you need to check that an odd number ends

`001`

? Isn't that handled by the`goodMask`

test?## @maaartinus 2014-07-11 14:55:13

@dfeuer I guess there are two reasons: 1. Shifting by more makes no sense. 2. It's like the HW works and anyone using bitwise operations is interested in performance, so doing anything else would be wrong.

-The`goodMask`

test does it, but it does itbeforethe right shift. So you'd have to repeat it, but this way it's simpler and AFAIK a tiny bit faster and equally good.## @dfeuer 2014-07-11 15:11:04

I missed the fact that you were shifting off the zeroes there. I guess the trailing zero count is too expensive to do first? Which architectures use only low-order bits for shifts?

## @maaartinus 2014-07-11 15:24:17

@dfeuer For the benchmark it's important to give answer ASAP, and the trailing zero count itself gives no answer; it's just a preparatory step. i86/amd64 do it. No idea about the small CPUs in mobiles, but at worst, Java has to generate an AND instruction for them, which is surely simpler than the other way round.

## @dfeuer 2014-07-13 10:29:19

Please take a look at my answer. If you could plug it into your benchmark system, I'd be very grateful.

## @durron597 2015-03-13 23:42:45

Can you post the full benchmark results, not just those 5?

## @Sebastian 2016-08-04 16:30:16

The third test

`if ((x&7) != 1 | x <= 0) return x == 0;`

could be`if ((x&7) != 1 | x < 0) return x == 0;`

(the case x==0 is already caught by`(x&7) != 1`

). I'm not sure if this speeds up the computation, but it makes it more obvious that you can remove the second test if your input is positive:`if ((x&7) != 1) return x == 0;`

I know there are no unsigned longs in java, but it might be helpful for people porting this code to other languages (like I'm doing right now).## @maaartinus 2016-08-04 16:57:15

@Sebastian I guess, you're right. However, IIRC the JIT made out of it something very different from what I was hoping for, so it may improve or worsen things. The problen with JIT is that the compiled code depends on data it was fed with, so aggregating the two cases didn't take place as I used no (hardly any?) negative inputs in my benchmark.

## @maaartinus 2016-08-04 16:59:05

@Sebastian A probably better test:

`if ((x & (7 | Integer.MIN_VALUE)) != 1) return x == 0;`

.## @Sebastian 2016-08-04 17:02:50

@maaartinus: I agree :) and then of course put

`(7 | Long.MIN_VALUE)`

in a constant (or assume the compiler is clever enough to do that for you)## @chux - Reinstate Monica 2017-03-23 14:51:21

"As double has only 56 bits mantissa" --> I would say it has more likely has a 53 bit one. Also

## @maaartinus 2017-07-30 22:36:36

@Sebastian It must be clever as it's a compile time constant according to the JLS.

## @Olivier Grégoire 2018-02-01 10:49:56

@maaartinus Dropbox says: "Sorry, that file doesn’t live here anymore. It might have been moved or made private." Would you post it here instead? Stackoverflow supports posts up to 40 KiB.Doesn't the file fit in?

## @maaartinus 2018-02-01 11:05:27

@OlivierGrégoire Sorry for that. I'll do it in two weeks, when I'm on the right machine again (it's offline, sorry!). The file surely fits. All my dropbox links broke, that's sad.

## @maaartinus 2018-02-15 20:21:15

@OlivierGrégoire I've fixed the link instead. The file has 22k and would fit, but I guess, the current link will for for a few years. I prefer not to post it here, as it's pretty long and boring, but feel free to edit, if you think otherwise.

## @maaartinus 2018-02-25 23:17:57

@OlivierGrégoire I'm just using it for projecteuler.net/problem=621 and that sad thing is that using nothing but the floating point test is equally good. :(

## @Nuwan Harshakumara Piyarathna 2020-04-26 09:25:04

How can I use this for very large numbers (BigIntegers).Then what will be the Mask value?How to calculate it?

## @maaartinus 2020-04-26 22:54:57

@NuwanHarshakumaraPiyarathna Both the

`goodMask`

and`numberOfTrailingZeros`

can be used in the same way (same value of`goodMask`

).## @Steve Storck 2017-10-12 23:08:19

Here is the simplest and most concise way, although I do not know how it compares in terms of CPU cycles. This works great if you only wish to know if the root is a whole number. If you really care if it is an integer, you can also figure that out. Here is a simple (and pure) function:

If you do not need micro-optimization, this answer is better in terms of simplicity and maintainability. If you will be getting negative numbers, perhaps you will want to use Math.abs() on the number argument as the Math.sqrt() argument.

On my 3.6Ghz Intel i7-4790 CPU, a run of this algorithm on 0 - 10,000,000 took an average of 35 - 37 nanoseconds per calculation. I did 10 sequential runs, printing the average time spent on each of the ten million sqrt calculations. Each total run took just a little over 600 ms to complete.

If you are performing a lesser number of calculations, the earlier calculations take a bit longer.

## @Stefan Reich 2017-12-04 12:52:28

I think you mean

`(long) Math.pow(roundedRoot, 2)`

## @Steve Storck 2017-12-05 11:03:23

I updated this soltution/suggestion to be the simplest way to figure it out. I wonder how it would compare in terms of benchmark against some of the custom solutions.

## @aventurin 2018-10-13 21:44:59

Your method returns

`true`

for`10_000_000_000_000_000L`

and`10_000_000_000_000_001L`

which proves that it't wrong.## @dfeuer 2014-07-13 10:17:15

The following simplification of maaartinus's solution appears to shave a few percentage points off the runtime, but I'm not good enough at benchmarking to produce a benchmark I can trust:

It would be worth checking how omitting the first test,

would affect performance.

## @maaartinus 2014-07-16 11:45:46

The results are here. Removing the first test is bad as it solves most cases pretty cheaply. The source is in my answer (updated).

## @A. Rex 2009-01-08 16:32:42

I figured out a method that works ~35% faster than your 6bits+Carmack+sqrt code, at least with my CPU (x86) and programming language (C/C++). Your results may vary, especially because I don't know how the Java factor will play out.

My approach is threefold:

`int64 x`

.)`z = r - x * x`

, and set t to be the largest power of 2 dividing z with a bit trick. This allows me to skip t values that wouldn't have affected the value of r anyway. The precomputed start value in my case picks out the "smallest positive" square root modulo 8192.Even if this code doesn't work faster for you, I hope you enjoy some of the ideas it contains. Complete, tested code follows, including the precomputed tables.

## @Kip 2009-01-12 21:47:11

Wow! I'll try to convert this to Java and do a comparison, as well as an accuracy check on the results. I'll let you know what I find.

## @Kip 2009-01-16 20:13:52

Testing on all values is impossible, but a test on suspect values (+/- 1 from very large perfect squares) has proven to be accurate. On a run of the first billion integers, this only took 34% of the time required by the original algorithm.

## @A. Rex 2009-01-16 20:50:31

Awesome! I'm glad it worked out for you. One thing that's different in C(++) and Java is that Java checks bounds on array lookups, so I thought you might take a hit there.

## @Dimitre Novatchev 2009-03-27 23:44:55

Seems that this only returns true/false, but it will be difficult to return the square root itself?

## @ShreevatsaR 2009-05-25 02:36:58

Wow, this is beautiful. I'd seen Hensel lifting before (computing roots of polynomials modulo a prime) but I hadn't even realised the lemma could be carefully lowered all the way for computing square roots of numbers; this is... uplifting :)

## @A. Rex 2009-12-03 23:50:42

@Dimitre Novatchev: No, it would not be too difficult. If the number is a perfect square, then its square root is

`r`

times some power of 2, which can be determined when dividing out by powers of 4.## @PeterT 2011-01-11 15:08:22

@A. Rex: HotSpot is able to eliminate bounds checks in certain circumstances stackoverflow.com/questions/4469483/bounds-checking-in-java so the hit is probably being avoided.

## @orlp 2012-09-17 08:20:45

@A. Rex: I might be mistaken, but isn't 9 a perfect square? And doesn't

`if( x < 0 || (x&2) || ((x & 7) == 5) || ((x & 11) == 8) ) return false;`

filter it out as not being one? And similar for all other uneven perfect squares?## @primo 2012-12-02 07:56:56

@nightcracker It doesn't.

`9 < 0 => false`

,`9&2 => 0`

,`9&7 == 5 => false`

,`9&11 == 8 => false`

.## @Jason C 2014-03-17 03:46:49

Maartinus posted a 2x faster solution (and much shorter) down below, a bit later, that doesn't seem to be getting much love.

## @maaartinus 2014-06-13 19:21:45

@A.Rex AFAIK, the final test

`t <= (1LL << 33)`

is useless as you either get a square root or overshoot anyway. I dropped it and it works (but maybe there's a gotcha with numbers I haven't tried?).## @user1914292 2014-10-07 17:26:16

It seems like a lot of the speed advantage in the different solutions is gained by filtering out the obvious squares. Did anyone benchmark the situation of filtering out via Maartinus' solution and then just using the sqrt function as that's a built-in function?

## @chux - Reinstate Monica 2018-05-21 08:30:05

`LL`

in`y & 4294967295LL`

not needed.## @Maëlan 2019-09-29 15:31:48

“Next, check if it's a square modulo 255 = 3 * 5 * 17. Because that's a product of three distinct primes, only about 1/8 of the residues mod 255 are squares.” Actually, the proportion of squares modulo 255 is 54/255 ≃ 0.212, much more than 1/8 = 0.125 (because the proportion of squares modulo each of the prime factors are slightly more than 1/2). But note that you are not limited to primes. The proportion of squares modulo 256 is 44/256 ≃ 0.172, and computing modulo 256 is much more convenient.

## @Maëlan 2019-09-29 15:50:33

That’s essentially one of the things maaartinus’ answer does, except that it uses 64 instead of 256 (which gives a more compact precomputed table with a better cache behavior, while still being pretty efficient at filtering out non-squares, as the proportion of squares modulo 64 is 12/64 ≃ 0.188).

## @Colonel Panic 2013-10-15 15:48:34

An integer problem deserves an integer solution. Thus

Do binary search on the (non-negative) integers to find the greatest integer t such that

`t**2 <= n`

. Then test whether`r**2 = n`

exactly. This takes time O(log n).If you don't know how to binary search the positive integers because the set is unbounded, it's easy. You starting by computing your increasing function f (above

`f(t) = t**2 - n`

) on powers of two. When you see it turn positive, you've found an upper bound. Then you can do standard binary search.## @user2975337 2015-07-14 02:05:18

Actually the time would be at least

`O((log n)^2)`

because multiplication is not constant-time but in fact has a lower bound of`O(log n)`

, which becomes apparent when working with large multi-precision numbers. But the scope of this wiki seems to be 64-bits, so maybe it's nbd.## @durron597 2013-06-10 16:39:07

I ran my own analysis of several of the algorithms in this thread and came up with some new results. You can see those old results in the edit history of this answer, but they're not accurate, as I made a mistake, and wasted time analyzing several algorithms which aren't close. However, pulling lessons from several different answers, I now have two algorithms that crush the "winner" of this thread. Here's the core thing I do differently than everyone else:

However, this simple line, which most of the time adds one or two very fast instructions, greatly simplifies the

`switch-case`

statement into one if statement. However, it can add to the runtime if many of the tested numbers have significant power-of-two factors.The algorithms below are as follows:

Internet- Kip's posted answerDurron- My modified answer using the one-pass answer as a baseDurronTwo- My modified answer using the two-pass answer (by @JohnnyHeggheim), with some other slight modifications.Here is a sample runtime if the numbers are generated using

`Math.abs(java.util.Random.nextLong())`

And here is a sample runtime if it's run on the first million longs only:

As you can see,

`DurronTwo`

does better for large inputs, because it gets to use the magic trick very very often, but gets clobbered compared to the first algorithm and`Math.sqrt`

because the numbers are so much smaller. Meanwhile, the simpler`Durron`

is a huge winner because it never has to divide by 4 many many times in the first million numbers.Here's

`Durron`

:And

`DurronTwo`

And my benchmark harness: (Requires Google caliper 0.1-rc5)

UPDATE:I've made a new algorithm that is faster in some scenarios, slower in others, I've gotten different benchmarks based on different inputs. If we calculate modulo`0xFFFFFF = 3 x 3 x 5 x 7 x 13 x 17 x 241`

, we can eliminate 97.82% of numbers that cannot be squares. This can be (sort of) done in one line, with 5 bitwise operations:The resulting index is either 1) the residue, 2) the residue

`+ 0xFFFFFF`

, or 3) the residue`+ 0x1FFFFFE`

. Of course, we need to have a lookup table for residues modulo`0xFFFFFF`

, which is about a 3mb file (in this case stored as ascii text decimal numbers, not optimal but clearly improvable with a`ByteBuffer`

and so forth. But since that is precalculation it doesn't matter so much. You can find the file here (or generate it yourself):I load it into a

`boolean`

array like this:Example runtime. It beat

`Durron`

(version one) in every trial I ran.## @Peter Cordes 2015-08-21 02:05:13

A giant lookup table doesn't seem like a good idea. A cache miss is slower (~100 to 150 cycles) than the x86 hardware sqrt instruction (~20 cycles). Throughput-wise, you can sustain a lot of outstanding cache-misses, but you're still evicting other useful data. A huge lookup table would only be worth it if it was a LOT faster than any other option, and this function was the major factor in the performance of your whole program.

## @Swiss Frank 2018-10-30 19:09:40

@Peter Cordes, you should only have cache misses a few times initially, then it will all be in cache, right?

## @Peter Cordes 2018-10-30 22:13:02

@SwissFrank: is perfect-square checking the

onlything your program does? A lookup table can look good in a microbenchmark that calls it repeatedly in a tight loop, but in a real program that has other data in its working set, it's not good.## @Peter Cordes 2018-10-30 22:18:05

A bitmap of 0x1FFFFFE bits takes 4 mega-

bytesif stored as a packed bitmap. An L3 cachehiton a modern Intel desktop has > 40 cycles of latency, and worse on a big Xeon; longer than hardware sqrt+mul latency. If stored as abyte-map with 1 byte per value, it's about 32 MB; bigger than the L3 cache of anything but a many-core Xeon where all core share one huge cache. So if your inputs data has a uniform random distribution over a large enough range of inputs, you'll get lots of L2 cache misses even in a tight loop. (private per-core L2 on Intel is only 256k, with ~12 cycle latency.)## @Swiss Frank 2018-10-31 09:36:47

@Peter Cordes, the original poster seems to say that that this is the core part of his program. As a recreational mathematician he may not be running any other processes while this is going, so it could be expected to have the cache much to itself. However if I understand your numbers, if you can't get it in L2--and you can't--then sqrt will be faster than going to L3. Off subject but do you have a convenient reference for access times on various CPUs?

## @Peter Cordes 2018-10-31 09:47:39

@SwissFrank: Oh, if all you're doing is root checking, then there's potential to this with a bitmap to get L3 hits. I was looking at latency, but many misses can be in flight at once, so throughput is potentially good. OTOH, SIMD

`sqrtps`

throughput or even`sqrtpd`

(double-precision) is not too bad on Skylake, but is not much better than latency on old CPUs. Anyway 7-cpu.com/cpu/Haswell.html has some nice experimental numbers, and pages for other CPUs. Agner Fog's microarch guide pdf has some cache latency numbers for Intel and AMD uarches: agner.org/optimize## @Peter Cordes 2018-10-31 09:52:38

Using x86 SIMD from Java is a problem, and by the time you add in the cost of int->fp and fp->int conversion, it's plausible that a bitmap could be better. You do need

`double`

precision to avoid rounding some integer outside the +-2^24 range (so a 32-bit integer can be outside that), and`sqrtpd`

is slower than`sqrtps`

as well as only processing half as many elements per instruction (per SIMD vector).## @Swiss Frank 2018-10-31 14:45:57

> "by the time you add in the cost of int->fp and fp->int conversion, it's plausible that a bitmap could be better" Just checked your profile, many bows! One idea that comes to mind is running your loop in int and double side by side, using the double where you need it and int where you need it. I totally haven't checked whether that even fits the wider discussion, but is just one thing I've done. BTW I do synthesizer software and am keen to try SIMD for one aspect of it...

## @chakrit 2008-11-17 13:50:19

I was thinking about the horrible times I've spent in Numerical Analysis course.

And then I remember, there was this function circling around the 'net from the Quake Source code:

Which basically calculates a square root, using Newton's approximation function (cant remember the exact name).

It should be usable and might even be faster, it's from one of the phenomenal id software's game!

It's written in C++ but it should not be too hard to reuse the same technique in Java once you get the idea:

I originally found it at: http://www.codemaestro.com/reviews/9

Newton's method explained at wikipedia: http://en.wikipedia.org/wiki/Newton%27s_method

You can follow the link for more explanation of how it works, but if you don't care much, then this is roughly what I remember from reading the blog and from taking the Numerical Analysis course:

`* (long*) &y`

is basically a fast convert-to-long function so integer operations can be applied on the raw bytes.`0x5f3759df - (i >> 1);`

line is a pre-calculated seed value for the approximation function.`* (float*) &i`

converts the value back to floating point.`y = y * ( threehalfs - ( x2 * y * y ) )`

line bascially iterates the value over the function again.The approximation function gives more precise values the more you iterate the function over the result. In Quake's case, one iteration is "good enough", but if it wasn't for you... then you could add as much iteration as you need.

This should be faster because it reduces the number of division operations done in naive square rooting down to a simple divide by 2 (actually a

`* 0.5F`

multiply operation) and replace it with a few fixed number of multiplication operations instead.## @Kip 2008-11-17 19:56:52

It should be noted that this returns 1/sqrt(number), not sqrt(number). I've done some testing, and this fails starting at n=410881: the John Carmack magic formula returns 642.00104, when the actual square root is 641.

## @user21037 2008-12-02 10:24:59

You could look at Chris Lomonts paper on fast inverse square roots: lomont.org/Math/Papers/2003/InvSqrt.pdf It uses the same technique as here, but with a different magic number. The paper explains why the magic number was chosen.

## @user21037 2008-12-02 10:26:33

Also, beyond3d.com/content/articles/8 and beyond3d.com/content/articles/15 shed some light as to the origins of this method. It's often attributed to John Carmack, but it seems the original code was (possibly) written by Gary Tarolli, Greg Walsh and probably others.

## @Antimony 2013-08-27 14:29:43

Also you can't typepun floats and ints in Java.

## @corsiKa 2015-05-27 17:50:52

@Antimony who says? FloatToIntBits and IntToFloatBits have been around since java 1.0.2.

## @Fractaly 2011-12-04 04:30:52

I checked all of the possible results when the last n bits of a square is observed. By successively examining more bits, up to 5/6th of inputs can be eliminated. I actually designed this to implement Fermat's Factorization algorithm, and it is very fast there.

The last bit of pseudocode can be used to extend the tests to eliminate more values. The tests above are for k = 0, 1, 2, 3

It first tests whether it has a square residual with moduli of power of two, then it tests based on a final modulus, then it uses the Math.sqrt to do a final test. I came up with the idea from the top post, and attempted to extend upon it. I appreciate any comments or suggestions.

Update:Using the test by a modulus, (modSq) and a modulus base of 44352, my test runs in 96% of the time of the one in the OP's update for numbers up to 1,000,000,000.## @finnw 2010-05-06 13:29:10

This is the fastest Java implementation I could come up with, using a combination of techniques suggested by others in this thread.

I also experimented with these modifications but they did not help performance:

## @paulmurray 2009-02-22 06:22:01

It ought to be possible to pack the 'cannot be a perfect square if the last X digits are N' much more efficiently than that! I'll use java 32 bit ints, and produce enough data to check the last 16 bits of the number - that's 2048 hexadecimal int values.

...

Ok. Either I have run into some number theory that is a little beyond me, or there is a bug in my code. In any case, here is the code:

and here are the results:

(ed: elided for poor performance in prettify.js; view revision history to see.)

## @dstibbe 2009-09-24 09:46:57

"I'm looking for the fastest way to determine if a long value is a perfect square (i.e. its square root is another integer)."

The answers are impressive, but I failed to see a simple check :

check whether the first number on the right of the long it a member of the set (0,1,4,5,6,9) . If it is not, then it cannot possibly be a 'perfect square' .

eg.

4567 - cannot be a perfect square.

## @Kip 2009-09-24 13:42:31

actually this has been suggested, only in different bases. Checking the last base-10 digit requires taking

`n%10`

, which is a division (and thus expensive). Besides, this would only eliminate 40% of possible values. In base-16, you can find the last hex-digit with`n&0xf`

, which is a very fast bit-wise operation. In base 16, the last digit of a perfect square has to be 0, 1, 4, or 9, which means that 75% of numbers are eliminated by that check.## @Kip 2009-09-24 13:44:52

This is the line that checks that the last hex digit is either 0, 1, 4, or 9, though it's using some optimized bit tricks to do it:

`if( n < 0 || ((n&2) != 0) || ((n & 7) == 5) || ((n & 11) == 8) )`

## @dstibbe 2009-09-25 09:47:42

Perhaps the following will be faster? Change: if( n < 0 || ((n&2) != 0) || ((n & 7) == 5) || ((n & 11) == 8) ) return false; if( n == 0 ) return true; into: if( n == 0 ) return true; if( n < 0 || !( ( n&7 == 1 ) || n==4 ) ) return false;

## @Jonny Heggheim 2009-05-25 01:22:28

I like the idea to use an almost correct method on some of the input. Here is a version with a higher "offset". The code seems to work and passes my simple test case.

Just replace your:

code with this one:

## @hydrodog 2009-03-11 13:25:05

The sqrt call is not perfectly accurate, as has been mentioned, but it's interesting and instructive that it doesn't blow away the other answers in terms of speed. After all, the sequence of assembly language instructions for a sqrt is tiny. Intel has a hardware instruction, which isn't used by Java I believe because it doesn't conform to IEEE.

So why is it slow? Because Java is actually calling a C routine through JNI, and it's actually slower to do so than to call a Java subroutine, which itself is slower than doing it inline. This is very annoying, and Java should have come up with a better solution, ie building in floating point library calls if necessary. Oh well.

In C++, I suspect all the complex alternatives would lose on speed, but I haven't checked them all. What I did, and what Java people will find usefull, is a simple hack, an extension of the special case testing suggested by A. Rex. Use a single long value as a bit array, which isn't bounds checked. That way, you have 64 bit boolean lookup.

The routine isPerfectSquare5 runs in about 1/3 the time on my core2 duo machine. I suspect that further tweaks along the same lines could reduce the time further on average, but every time you check, you are trading off more testing for more eliminating, so you can't go too much farther on that road.

Certainly, rather than having a separate test for negative, you could check the high 6 bits the same way.

Note that all I'm doing is eliminating possible squares, but when I have a potential case I have to call the original, inlined isPerfectSquare.

The init2 routine is called once to initialize the static values of pp1 and pp2. Note that in my implementation in C++, I'm using unsigned long long, so since you're signed, you'd have to use the >>> operator.

There is no intrinsic need to bounds check the array, but Java's optimizer has to figure this stuff out pretty quickly, so I don't blame them for that.

## @maaartinus 2013-09-08 19:18:36

I'd bet you're wrong twice. 1. Intel sqrt conforms to IEEE. The only non-conforming instructions are the goniometrical instructions for lange arguments. 2. Java uses intrinsics for Math.sqrt, no JNI.

## @maaartinus 2018-02-20 16:34:03

Didn't you forget to use

`pp2`

? I understand that`pp1`

is used for testing the six least significant bits, but I don't believe that testing the next six bits makes any sense.## @Ben 2009-03-11 13:18:14

Regarding the Carmac method, it seems like it would be quite easy just to iterate once more, which should double the number of digits of accuracy. It is, after all, an extremely truncated iterative method -- Newton's, with a very good first guess.

Regarding your current best, I see two micro-optimizations:

I.e:

Even better might be a simple

Obviously, it would be interesting to know how many numbers get culled at each checkpoint -- I rather doubt the checks are truly independent, which makes things tricky.

## @John D. Cook 2008-11-17 14:27:17

You'll have to do some benchmarking. The best algorithm will depend on the distribution of your inputs.

Your algorithm may be nearly optimal, but you might want to do a quick check to rule out some possibilities before calling your square root routine. For example, look at the last digit of your number in hex by doing a bit-wise "and." Perfect squares can only end in 0, 1, 4, or 9 in base 16, So for 75% of your inputs (assuming they are uniformly distributed) you can avoid a call to the square root in exchange for some very fast bit twiddling.

Kip benchmarked the following code implementing the hex trick. When testing numbers 1 through 100,000,000, this code ran twice as fast as the original.

When I tested the analogous code in C++, it actually ran slower than the original. However, when I eliminated the switch statement, the hex trick once again make the code twice as fast.

Eliminating the switch statement had little effect on the C# code.

## @warren 2008-11-17 14:38:07

that's pretty clever... wouldn't have thought of that

## @PeterAllenWebb 2008-11-17 14:56:44

Nice point about the trailing bits. I would try to combine that test with some of the other remarks here.

## @Kip 2008-11-17 16:09:54

I benchmarked it for the first 100 million integers.. this approximately halves the time required.

## @kenj0418 2010-02-08 04:41:52

You could extend this beyond the last digit as well. For example, there are only 44 different values the least significant byte can have.

## @Jeel Shah 2011-12-07 15:30:15

Superb solution. Wondering how you came up with it? Is a fairly established principle or just something you figured out? :D

## @LarsH 2013-10-17 14:43:34

FYI, I tested this method in Python. It gave about a 3/8 speedup over the vanilla

`t = math.floor(math.sqrt(n) + 0.5); return t*t == n`

(5 seconds vs. 8 seconds to compute for the first 100,000 integers, 100 times).## @maaartinus 2014-06-13 18:12:42

@LarsH There's no need to add 0.5, see my solution for a link to the proof.

## @JerryGoyal 2017-01-03 09:26:43

you said that if-else is faster than switch but this stackoverflow.com/questions/6805026/is-switch-faster-than-if question tells the different story.

## @fishinear 2017-11-10 16:56:34

@JerryGoyal It depends on the compiler and the values of the cases. In a perfect compiler, a switch is always at least as fast as if-else. But compilers are not perfect, so it is best to try it out, like John did.

## @Brent.Longborough 2009-01-01 22:27:43

This a rework from decimal to binary of the old Marchant calculator algorithm (sorry, I don't have a reference), in Ruby, adapted specifically for this question:

Here's a workup of something similar (please don't vote me down for coding style/smells or clunky O/O - it's the algorithm that counts, and C++ is not my home language). In this case, we're looking for residue == 0:

## @Tadmas 2009-01-02 00:24:34

The number of iterations looks O(ln n), where n is the bit-length of v, so I doubt this will save much for larger v. Floating point sqrt is slow, maybe 100-200 cycles, but integer math isn't free either. A dozen iterations with 15 cycles each, and it'd be a wash. Still, +1 for being interesting.

## @Brent.Longborough 2009-01-02 08:12:15

Actually, I believe the additions and subtractions can be done by XOR.

## @Brent.Longborough 2009-01-02 09:13:29

That was a daft comment - only the addition can be done by an XOR; the subtraction is arithmetic.

## @Tadmas 2009-01-02 22:59:34

Is there really any substantive difference between the run time of XOR and addition anyway?

## @Brent.Longborough 2009-01-04 00:17:51

@Tadmas: probably not enough to break the "optimise later" rule. (:-)

## @maaartinus 2018-02-20 16:27:19

@Tadmas No. While XOR is much simpler and faster in hardware, the cycle of any CPU is more than long enough for the addition. So you can't save anything unless you build your own circuit. +++ The slowest operation is actually the branching (pipeline work lost due to branch mispredictions) and this may be optimized away (a good compiler does it already).

## @David Lehavi 2009-01-01 22:12:38

You should get rid of the 2-power part of N right from the start.

2nd EditThe magical expression for m below should beand not as written

End of 2nd edit1st Edit:Minor improvement:

End of 1st editNow continue as usual. This way, by the time you get to the floating point part, you already got rid of all the numbers whose 2-power part is odd (about half), and then you only consider 1/8 of whats left. I.e. you run the floating point part on 6% of the numbers.

## @BobbyShaftoe 2008-12-05 05:36:38

For performance, you very often have to do some compromsies. Others have expressed various methods, however, you noted Carmack's hack was faster up to certain values of N. Then, you should check the "n" and if it is less than that number N, use Carmack's hack, else use some other method described in the answers here.

## @Kip 2008-12-05 19:56:34

I've incorporated your suggestion into the solution too. Also, nice handle. :)

## @Cyrille Ka 2008-12-02 10:00:22

Just for the record, another approach is to use the prime decomposition. If every factor of the decomposition is even, then the number is a perfect square. So what you want is to see if a number can be decomposed as a product of squares of prime numbers. Of course, you don't need to obtain such a decomposition, just to see if it exists.

First build a table of squares of prime numbers which are lower than 2^32. This is far smaller than a table of all integers up to this limit.

A solution would then be like this:

I guess it's a bit cryptic. What it does is checking in every step that the square of a prime number divide the input number. If it does then it divides the number by the square as long as it is possible, to remove this square from the prime decomposition. If by this process, we came to 1, then the input number was a decomposition of square of prime numbers. If the square becomes larger than the number itself, then there is no way this square, or any larger squares, can divide it, so the number can not be a decomposition of squares of prime numbers.

Given nowadays' sqrt done in hardware and the need to compute prime numbers here, I guess this solution is way slower. But it should give better results than solution with sqrt which won't work over 2^54, as says mrzl in his answer.

## @Peter Cordes 2015-08-21 02:22:01

integer division is slower than FP sqrt on current hardware. This idea has no chance. >.< Even in 2008, Core2's

`sqrtsd`

throughput is one per 6-58c. Its`idiv`

is one per 12-36cycles. (latencies similar to throughputs: neither unit is pipelined).## @Peter Cordes 2015-08-21 02:23:56

sqrt doesn't need to be perfectly accurate. That's why you check by integer-squaring the result and doing an integer-compare to decide if the input integer had an exact integer sqrt.

## @Hugh Allen 2008-11-29 03:52:36

It's been pointed out that the last

`d`

digits of a perfect square can only take on certain values. The last`d`

digits (in base`b`

) of a number`n`

is the same as the remainder when`n`

is divided by`b`

^{d}, ie. in C notation`n % pow(b, d)`

.This can be generalized to any modulus

`m`

, ie.`n % m`

can be used to rule out some percentage of numbers from being perfect squares. The modulus you are currently using is 64, which allows 12, ie. 19% of remainders, as possible squares. With a little coding I found the modulus 110880, which allows only 2016, ie. 1.8% of remainders as possible squares. So depending on the cost of a modulus operation (ie. division) and a table lookup versus a square root on your machine, using this modulus might be faster.By the way if Java has a way to store a packed array of bits for the lookup table, don't use it. 110880 32-bit words is not much RAM these days and fetching a machine word is going to be faster than fetching a single bit.

## @finnw 2010-01-07 12:28:07

Nice. Did you work this out algebraically or by trial and error? I can see why it's so effective - lots of collisions between perfect squares, e.g. 333^2 % 110880 == 3^2, 334^2 % 110880 == 26^2, 338^2 % 110880 == 58^2...

## @Hugh Allen 2010-01-19 01:18:52

IIRC it was brute force, but note that 110880 = 2^5 * 3^2 * 5 * 7 * 11, which gives 6*3*2*2*2 - 1 = 143 proper divisors.

## @Fractaly 2011-12-04 05:57:05

I found that because of the limitations of the lookup, 44352 works better, with a 2.6% pass rate. At least in my implementation.

## @Peter Cordes 2015-08-21 02:13:16

Integer division (

`idiv`

) is equal or worse in cost to FP sqrt (`sqrtsd`

) on current x86 hardware. Also, completely disagree with avoiding bitfields. Cache hit rate will be tons better with a bitfield, and testing a bit in a bitfield is only one or two more simple instructions than testing a whole byte. (For tiny tables that fit in cache even as non-bitfields, a byte array would be best, not 32bit ints. x86 has single-byte access with equal speed to 32bit dword.)