This is a question, regarding my homework, specifically on NASM.
I am writing an algorithm to find the least whole factor of a number. (Greater than 1)
In pseudo-code it can be summed up as:
if(n%2==0)
return 2;
for(i=3; i <= n/2; i+=2)
if(n%i==0)
return i;
return n;
The program is just slightly slower than the requirement for large numbers. (n
> 1 000 000 000)
The most obvious (to me) improvement would be replacing n/2
with sqrt(n)
. However I am not supposed to know how to use floating-point numbers and finding the integer sqrt by Newton's method seems overkill. (Because I don't actually need to know the exact value and although I haven't tested it, I would imagine finding the isqrt recursively/iteratively would be quite slow)
So I was wondering, whether there is a fast algorithm for some function, such that sqrt(n) < f(n) < n/2
. By "fast" I mean preferably constant time and by f(n) < n/2
I mean significantly less for big n
.
Some of the options I am considering are:
Check, for
i <= min(sqrt(2^32), n/2)
, wheresqrt(2^32) = 2^16
is a constant.Replace
i <= n/2
withi <= (2^p)
, wherep = ⌈log_2(n)/2⌉
or something. (p
is half the position of most significant bit ofn
)