[英]Prime Number Checker Written in C#
我已經放棄了數字生成器,因為我知道它實際上是將每個數字分開,直到它收到一個素數。 我已經更改了代碼,以便從指定范圍"a" to "?" (in this case, 10)
素數 Prime_2
方法中的"a" to "?" (in this case, 10)
在Prime_2
方法中被檢查為素數。 然后,如果該數字是素數,則通過將布爾變量prime設置為true或false來返回Prime方法,但到目前為止,我只得到2為真,其余為假。 這顯然不是真的。 因此,我感謝任何協助/意見/建議,使這個新計划可行。
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
}
如果你想通過試驗分區來檢查2到100之間的每個數字的原始性,這是你似乎要嘗試做的,使用這個偽代碼算法:
function isPrime(n)
if n % 2 == 0
return n == 2
d := 3
while d * d <= n
if n % d == 0
return False
d := d + 2
return True
這需要時間為O(n 1.5)用於找到素數多達n。 如果您想要更快的算法,請使用Eratosthenes的Sieve,即O(n log log n) :
function primes(n)
sieve := makeArray(2..n, True)
for p from 2 to n step 1
if sieve[p]
output p
for i from p*p to n step p
sieve[i] := False
如果你對使用素數編程感興趣,我謙虛地在我的博客上推薦這篇文章 。
我不確定你為什么要在你的功能中做你正在做的事情。 你能在代碼中添加一些注釋嗎? 但是,檢查素數的快速方法如下
bool IsPrime(int number) {
if (number % 2 == 0 && number != 2) return false; // Don't check even numbers
for (int i = 2; i < number; i++) {
if (number % i == 0 && i != number) return false;
}
return true;
}
當然,您應該在if語句中調用上面的函數,如果為true,則顯示數字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.