c# - Check if number is prime number -
i ask if correct way of checking if number prime or not? because read 0 , 1 not prime number.
int num1; console.writeline("accept number:"); num1 = convert.toint32(console.readline()); if (num1 == 0 || num1 == 1) { console.writeline(num1 + " not prime number"); console.readline(); } else { (int = 2; <= num1 / 2; a++) { if (num1 % == 0) { console.writeline(num1 + " not prime number"); return; } } console.writeline(num1 + " prime number"); console.readline(); }
var num1; console.writeline("accept number:"); num1 = convert.toint32(console.readline()); if(isprime(num1)) { console.writeline("it prime"); } else { console.writeline("it not prime"); } public static bool isprime(int number) { if (number == 1) return false; if (number == 2) return true; if (number % 2 == 0) return false; var boundary = (int)math.floor(math.sqrt(number)); (int = 3; <= boundary; i+=2) { if (number % == 0) return false; } return true; }
i changed number / 2
math.sqrt(number)
because in wikipedia, said:
this routine consists of dividing n each integer m greater 1 , less or equal square root of n. if result of of these divisions integer, n not prime, otherwise prime. indeed, if n = a*b composite (with , b ≠ 1) 1 of factors a or b @ square root of n
Comments
Post a Comment