MATLAB Answers

square root of a big number

14 views (last 30 days)
dedeff
dedeff on 14 Mar 2016
Commented: dedeff on 15 Mar 2016
Hi, How to calculate the square root of a big number, for example 2025027714713048816? How to test if a big number is a perfect sqare or not? Thanks

  0 Comments

Sign in to comment.

Accepted Answer

John D'Errico
John D'Errico on 15 Mar 2016
Edited: John D'Errico on 15 Mar 2016
As long as we can start with a uint64 number, this should work reasonably well:
N = uint64(2025027714713048816);
u = uint64(sqrt(double(N)))
u =
1423034685
Then perform this iteratively, UNTIL u converges:
u = (u + N/u)/2
u =
1423034685
Wrapping a while loop around it would suffice, but it should not take many iterations. See that the double sqrt has in fact arrived at the proper (approximate) sqrt, with no extra steps required at all.
u*u
ans =
2025027714713049225
So, not exact, but as close as we can get to the true square root in integers.
vpa(sqrt(sym(N)))
ans =
1423034684.9999998562930319579666

  1 Comment

dedeff
dedeff on 15 Mar 2016
Hi John D'Errico,
vpa(sqrt(sym(N))) is a perfect solution for my problem.
Thanks

Sign in to comment.

More Answers (2)

James Tursa
James Tursa on 14 Mar 2016
You can use the Symbolic Toolbox for this, or use this FEX submission by John D'Errico:

  0 Comments

Sign in to comment.


Walter Roberson
Walter Roberson on 14 Mar 2016
With some tricks you can find the integer portion of the square root of any integer up to 2^64-1 using fzero. Once you have the integer portion, you can square it and compare it to the original value: if they matched then it was a perfect square.
The tricks are not immediately obvious, though. They involve compensating for the fact that a calculation on uint64 cannot go negative, by doing arithmetic on the results of logical tests.

  0 Comments

Sign in to comment.