Я отказался от генератора чисел, потому что я понимаю, что он фактически делит каждое число, пока не получит простое число. Я изменил код так, что простые числа из заданного диапазона "a" to "?" (in this case, 10)
в методе Prime_2
проверяются как простые в методе Prime. Тогда метод Prime возвращает, если это число является простым, задавая логическую переменную prime, true или false, но до сих пор я получил значение true для 2 и false для остальных. Это, очевидно, не так. Поэтому я был бы признателен за любую помощь/комментарии/предложения в том, чтобы сделать эту новую программу работоспособной.Prime Number Checker Написано на C#
public bool Prime(long num) // Prime method with a parameter for one number
{
int div = 3; // what we divide by after checking if the number is divisible by 2
bool prime = true; // set prime to true
{
for (long i = 0; i < 100 && prime == true; i++) // run 100 passes
{
if (num % 2 == 0 && num != 2) // if the number is divisible by 2
{ // and is not 2, prime is false.
prime = false;
}
else if (num % 2 != 0 && num != 2) // if the number is not divisible
{ // by 2 and the number is not 2...
for (long x = 0; x <= 1000; x++) // then run 1000 passes of this:
{
if (num % Math.Pow((div), x) == 0 && num != Math.Pow((div), x))
{ // if the number is divisible by our div to the power of x
// and the number is not equal to div to the power of x,
// prime is false.
prime = false;
}
}
}
else // otherwise add 2 to div making it the next consecutive odd number
{ // and run the pass again
div = div + 2;
}
}
return prime;
}
}
public void Prime_2() // void Prime_2 method
{
long a = 2; // starting number 2
long b = 0; // set b
Program prg = new Program(); //new instance of the Program class
while (a <= 10)//the range a (2) - 10
{
b = a;//set "b" to "a" every time
prg.Prime(b); // run the Prime method for numbers 2-10
Console.WriteLine(b); // write the number being checked
Console.WriteLine(prg.Prime(b)); // return if it is true or false for prime
a++; // add 1 to a
}
}
static void Main(string[] args)
{
Program prog = new Program(); // instantiate a new Program
prog.Prime_2(); // run the method, Prime_2
Console.ReadLine(); // wait for input
}
Вы действительно должны использовать 'yield return' ... –
Вы изменяете число внутри вашей функции проверки. Похоже, вы пытаетесь найти простое число, которое меньше заданного числа. –