我已经放弃了数字生成器,因为我知道它实际上是对每个数字进行除法,直到它收到一个素数。我更改了代码,以便将方法中指定范围内"a" to "?" (in this case, 10)
的素数Prime_2
检查为 Prime 方法中的素数。然后 Prime 方法通过将布尔变量 prime 设置为 true 或 false 来返回该数字是否为素数,但到目前为止,我只得到了 2 的 true 和其余的 false。这显然不是真的。因此,我将不胜感激任何帮助/意见/建议使这个新程序可行。
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
}