Home > Enterprise >  c# array in prime numbers - Where is my mistake?
c# array in prime numbers - Where is my mistake?

Time:10-03

//I want to fill an array with the first 15 prime numbers. the loop will only increase as you find the prime number and add it to the array.

 int[] primes = new int[15];
    int j = 0;
    int i = 2;
    while (j < 15)
    {
        if (IsPrime(i))
        {
            primes[j] = i;
            j  ;
        }
        i  ;
    }
    for (int a = 0; a < primes.Length; a  )
    {
        Console.Write(primes[a]   " ");
    }
}

//method

static bool IsPrime(int number)
{
    for (int i = 2; i < number; i  )
    {
        if (number % i == 0)
        {
            return true;
        }
    }
    return false;
} 

CodePudding user response:

Problem is that your IsPrime function is actually doing the exact oposite of what you want to achieve. Look at that function again and think about where the mistake is (hint: it is a minor problem, I feel like you just overlooked something and that the logic in your mind was correct).

After you get the result you want, I also recommend you to think about IsPrime function again and try to optimize it a little bit (hint: do you really need to test all the numbers, one by one?) and also to your while loop (hint: do you really need to iterate i by 1?).

Also welcome to Stackoverflow!

CodePudding user response:

You have to fix the IsPrime function as follows:

static bool IsPrime(int number)
{
    int i;  
    for (i = 2; i <= number - 1; i  )  
    {  
        if (number % i == 0)  
        {
            return false;  
        }  
    }  
    if (i == number)  
    {  
        return true;  
    }  
    return false; 
} 

Output

2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

  •  Tags:  
  • c#
  • Related