Hi friends , i have some code for to find out whether the no is prime or not. but i want it in c# using the same logic.

``````int isPrime(int n) {
int c =0, s=0;

if (n == 1) { return 0; }
if (n == 2) { return 1; }
if (n % 2 == 0) { return 0; }

s = (int)sqrt( (double)n );

for (c=3; c < s; c+=2) {
if (n % c == 0) {return 0;}
}
return 1;
}
``````

Edited by Nick Evan: Fixed formatting

3
Contributors
2
Replies
4
Views
6 Years
Discussion Span
Last Post by Momerath

This is C code, very little needs to be changed.
Change sqrt to Math.Sqrt.
I would not return an int but a boolean so the last lines should return ture or false and your method should return a boolean type off cource.

Just FYI, your code has a bug in it. Any odd number that is the square of a prime will show as a prime. I've fixed that in the below code.

``````Boolean IsPrime(int n) {
Boolean result = true;
if (n == 1) {
result = false;
} else if (n % 2 == 0 && n != 2) {
result = false;
} else {
int limit = (int)Math.Sqrt(n);
for (int i = 3; i <= limit; i += 2) {
if (n % i == 0) {
result = false;
break;
}
}
}

return result;
}``````

Edited by Momerath: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.