Finding whether a number is Prime or not by limiting the number of iterations-c# -
I have to find out whether a number is prime or not as limited by the number of iterations as possible. The following program was suggested in a blog. I can understand these parts of the code.
Public stable bull isprrome (long) {if (i == 1) {return false; } And if (i & lt; 4) {back true; } And if (i% 2 == 0) {return false; } And if (i & lt; 9) {back true; } And if (i% 3 == 0) {return false; }
But I do not understand why f
grows by 6.
else {double r = Math.Floor (Math.Sqrt (i)); Int f = 5; While (F & LT; = R) {if (i% f == 0) {return false; } If (i% (f + 2) == 0) {return false; } F = f + 6; } Back true; }}
Because every major number (excluding 2 and 3) is of form 6k +/- 1 Each second number can not be predominant, because they are divisible by 2 or 3, as well as some modifications in your method:
Public stable bull ISSprime (long I) {if (I & lt; 2) {return false; } And if (i & lt; 4) {back true; } And if ((i and amp; 1) == 0) {return false; } And if (i & lt; 9) {back true; } And if (i% 3 == 0) {return false; } Else {double r = Math.Floor (Math.Sqrt (i)); Int f = 5; While (F & LT; = R) {if (i% f == 0) {return false; } If (i% (f + 2) == 0) {return false; } F = f + 6; } Back true; }}
- You did not check the negative numbers
- To check that there is also a number, (i & amp; 1) == 0 More efficient Unfortunately, I do not have any such move for% 3
Comments
Post a Comment