x=1;
y=0;
while x:N
if mod(sqrt(x), 1)==0;
y=y+1
end
x=x+1
end
This is roughly what I'm trying to do. Can you guys show me my errors and how to fix them? Thanks as always.
N = 70;
x = 1;
while x <= N
if rem(sqrt(x), 1) <= eps
fprintf('%d is a perfect square.\n', x);
else
fprintf('%d is NOT a perfect square.\n', x);
end
x=x+1;
end
I would go:
x = 1;
y = 0;
while x <= N
if rem(sqrt(x), 1) <= eps
y = y + 1;
x = x + sqrt(x);
end
x = x + 1;
end
Since if x is a perfect square no other "Perfect Square" would be in sqrt(x) range.
x = x + ceil(sqrt(x));
For even more speedup, we could do
x=(sqrt(x)+1)^2 - 1 % ;-)
and I still don't know why that "y" is in there.
Yea, You got where I got my Speed Up idea from :-).
It is recommended to use you corrections.
count = 1;
while count<= sqrt(N)-1
count = count + 1;
end
"Matt Fig" <spam...@yahoo.com> wrote in message
news:i80pq8$g8q$1...@fred.mathworks.com...
If you were looking to do this without SQRT, you could use the second
equation given on this page:
http://en.wikipedia.org/wiki/Square_number
function numSquares = countsquares(N)
numSquares = 0;
currentSquare = 1;
increment = 3;
while currentSquare <= N
numSquares = numSquares + 1;
currentSquare = currentSquare + increment;
increment = increment + 2;
end
This handles negative and noninteger values for N; add error checking for
complex, nonfinite, or nonscalar N to taste.
--
Steve Lord
sl...@mathworks.com
comp.soft-sys.matlab (CSSM) FAQ: http://matlabwiki.mathworks.com/MATLAB_FAQ
To contact Technical Support use the Contact Us link on
http://www.mathworks.com
Why? Isn't the answer always floor(sqrt(N))
"ImageAnalyst" <imagea...@mailinator.com> wrote in message
news:3e598046-0b28-431d...@p1g2000yqm.googlegroups.com...
In either case, since the message refers to C but not MATLAB, the message
should probably have been posted on a different newsgroup like comp.lang.c
(or should not have been posted at all.)
--
Steve Lord
sl...@mathworks.com