It can then run on the simplest hardware or microcontroller.
Has anyone seen any similar / \ Div free code ?
The number here is represented in the form; n = a * b + c.
It searches for c = 0, when a and b will be factors.
This compact code can run fast in the CPU registers.
Comparisons are fast because all registers are the same length.
It produces a list of prime factors increasing in size.
This simple algorithm could be improved. It is inefficient because:
1. It goes around the loop very many times, so it does not like really big numbers.
2. It tests all even candidates, when it could do a two step.
3. After finding a prime factor, p, it begins again from scratch, not at p.
Here is the code inside a loop that exercises it for a block of numbers.
Code: Select all
' Prime Factors without using DIV or MOD
' n = ( a * b ) + c, when c = 0, a and b are factors
Dim As Ulong a, b, c, n, i = 2^20
Print " Prime Factors."
For n = i - 9 To i + 9
Print n; " = ";
a = n ' n = a * b + c
b = 1 ' trial factor
c = 0 ' mod, remainder
Do
a -= 1
c += b
If c >= a Then ' carry
b += 1
c -= a
End If
If c = 0 Then ' b is a factor
Print b; " * ";
b = 1
End If
Loop While b < a ' square root
Print a * b + c ' terminal factor may be 1
Next n
Print " Done."
Sleep