Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

c# array in prime numbers – Where is my mistake?

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading