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;
}

Thanks in advance.

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;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.