简体   繁体   中英

((i % 2 == 0) && (i % i == 0)) this technique will not work for generating Prime number c#

Hi, I am trying to generate a prime number, but my condition i%i is producing an error.

I am getting the error "attempt to divide by zero".

How would I fix this??

int a, n, i;

Console.WriteLine("Enter ur number");

n = Convert.ToInt32(Console.ReadLine());

for (i = 0; i <= n; i++)
{
    if ((i % 2 == 0) && (i % i == 0))
    {
        a = i;
        Console.WriteLine("The prime numbers are", a);
    }
}

Console.ReadLine();

Hoping to listen from you soon...

When i is zero, first time around the loop you are doing 0 % 0 which results in a divide by zero error.

As for what your function is trying to do, I've no idea. I don't see anything much related to prime numbers here. You are simply finding out all the even numbers less than n .

Let's have a look at the if test:

if ((i % 2 == 0) && (i % i == 0))

The second part, i % i == 0 will always be true so long as i is not 0 . So that part is spurious. And i % 2 == 0 simply tests whether or not i is even.

What is your code actually intending to do? Are you trying to test whether or not a number is prime? If so, the simplest approach is like this:

static bool isPrime(int n)
{
    Debug.Assert(n>0);
    for (int i=2; i<n; i++)
        if (n % i == 0) // n is exactly divisible by i, so n is not prime
            return false;
    return true; // we could not find a factor, so n must be prime
}

You current code cannot output any numbers because your call to Console.WriteLine is not quite correct. You mean:

Console.WriteLine("The prime numbers are: {0}", a);

The other point to make is that your version of the code mixed the primality test in with the I/O code. Mixing it all together in one big routine makes it harder for you to understand and debug the code. Split the primality test into a separate function as I illustrate here and you can more easily check its correctness. Once you know it is correct, you can use it from your IO code. And then you can concentrate on getting your IO code correct. Which could look something like this:

Console.Write("Enter your number: ");
int n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("The prime numbers are:");
for (int i = 1; i <= n; i++)
    if (isPrime(i))
        Console.WriteLine(i);
Console.ReadLine();

Change

for (i = 0; i <= n; i++)

to

for (i = 1; i <= n; i++)

Well, when i is 0, you're trying to calculate 0%0 , which is indeed an attempt to divide by zero.

Anyway, except when i is 0, i%i is always 0. That's hardly the way to calculate prime numbers.

% is the modulus operator. It gives the remainder of the division between the two numbers.

(i % 2) == 0

will test whether i is even.

(i % i) == 0

will always return true for i > 0 , because i / i = 1 remainder 0 . When i is 0 , you will get a divide by zero exception, because you are attempting to evaluate 0 / 0 .

(see also: http://msdn.microsoft.com/en-us/library/0w4e0fzs.aspx )

To determine whether i is prime, you would want to make sure that i is not divisible by all integers from 2 to floor(i / 2) .

It's obvious because you are starting loop from 0, you should start your loop from 1.

A kids program to find prime in C is

#include<stdio.h>

main()
{
   int n, c = 2;

   printf("Enter a number to check if it is prime\n");
   scanf("%d",&n);

   for ( c = 2 ; c <= n - 1 ; c++ )
   {
      if ( n%c == 0 )
      {
         printf("%d is not prime.\n", n);
     break;
      }
   }
   if ( c == n )
      printf("%d is prime.\n", n);

   return 0;
}

When you are checking for prime no: Check this what are the prime numbers .

Prime number are those which will not divided by any number except 1 and itself.

By the statement your checking number should start from 2 to N-1.

 bool isPrime = true;
            int number = Convert.ToInt32(Console.Read());
            int i = 2;
            while (i < number)
            {
                if (number % i == 0)
                {
                    isPrime = false;
                    break;
                }
                i++;
            }

            if (isPrime)
            {
                //Prime number
            }
            else
            {
                //Not Prime No
            }

Check this to know how to generate prime numbers between some range 1 - 100 etc. to do so you have to put prime checking loop inside another counter loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM