一個數是否是質數,就是判斷一個數除了1和它自己還有沒有其餘的約數,若是有則是合數,不然是質數。其實本質都是求公約數。算法
求公約數是什麼思路呢,就是找比它小的數不斷嘗試,能被整除則是其約數,不然繼續嘗試,直到肯定全部數都找遍。本着這個思路,求公約數的算法以下:spa
public static List<long> GetGYS(long num) { if(num==1) return new List<long>(){1}; var list=new List<long>(){1,num}; long temp=2,end=num/temp; while(temp<end){ if(num%temp==0) list.Add(temp); temp++; end=num/temp; } return list; }
後來想了想,若是單純求是否爲質數,其實還能夠更快速一些,把步進調整爲2,以下:code
public static bool CheckedIsZS(long num) { if(num<=3) return true; if(num%2==0) return false; long temp=3,end=num/temp; while(temp<end){ if(num%temp==0) return false temp+=2; end=num/temp; } return true; }