简体   繁体   中英

I'm in need of help for a prime counting program with no error, howerver still crashing (C#)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Pi_szamlalo
{
    class Program
    {
        static void Main(string[] args)
        {
            int limit = 100;
            List<int> prime = new List<int>();
            prime.Add(2);
            for (int number = 3; number <= limit; number = number + 1)
            {
                foreach(int prime2 in prime) //here is the error at "in"
                {
                    if (number % prime2 == 0)
                    {
                        Console.WriteLine(number + " is not a prime");
                    }
                    else
                    {
                        Console.WriteLine(number + " is a prime");
                        prime.Add(number);
                    }
                }
            }
            Console.ReadKey();
        }
    }
}

The idea would be that the program tries to divide all the whole numbers to the limit with the already known primes. If the remainder is zero in one of the cases, the program will move on to the next.

However, if the program could not find a prime number in the list of primes, it will add it to the list, and say it's a prime.

So, in Visual Studio 2013, there are no sign of errors, except the crash. Here is the error message The Error message

It is in hungarian, it says something like this: The list has been modified, it may be that the operation cannot be runned.

Here's a working example taking into account my comment above: you need to run through the whole list of primes before deciding if a number is prime - currently you're writing whether it is or isn't a prime each time you test it: you can only determine that when you've finished testing.

class Program
{
    static void Main(string[] args)
    {
        int limit = 100;
        List<int> prime = new List<int>();
        prime.Add(2);
        for (int number = 3; number <= limit; number = number + 1)
        {
            bool isPrime = true;

            foreach (int prime2 in prime)
            {
                if (number % prime2 == 0)
                {
                    isPrime = false;
                    break;
                }
            }

            if (isPrime)
            {
                Console.WriteLine(number + " is a prime");
                prime.Add(number);
            }
            else
            {
                Console.WriteLine(number + " is not a prime");
            }
        }
    }
}

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