c# - Largest Prime Factor algorithm optimization -
i'm trying improve interesting algorithm as can.
for now, have this:
using system; class program { static void main() { ulong num, largest_pfact; uint = 2; string strnum; console.write("enter number: "); strnum = console.readline(); num = ulong.parse(strnum); largest_pfact = num; while (i < math.sqrt((double) largest_pfact)) { if (i % 2 != 0 | == 2) { if (largest_pfact % == 0) largest_pfact /= i; } i++; } console.writeline("largest prime factor of {0} is: {1}", num, largest_pfact); console.readline(); } }
so ideas?
thanks!
edit: implemented ben's algorithm, eveyone help!
i've got faster algorithm here.
it eliminates square root , handles repeated factors correctly.
optimizing further:
static private ulong maxfactor (ulong n) { unchecked { while (n > 3 && 0 == (n & 1)) n >>= 1; uint k = 3; ulong k2 = 9; ulong delta = 16; while (k2 <= n) { if (n % k == 0) { n /= k; } else { k += 2; if (k2 + delta < delta) return n; k2 += delta; delta += 8; } } } return n; }
here's working demo: http://ideone.com/sicil
Comments
Post a Comment