所以,这个控制台应用程序只打印一个数字是否是素数,几乎适用于每个数字,但是当要求分配使用两个硬编码数字(7389274937501454911 和 9389274937501454911)对函数进行时间测试时,这些数字不会打印出任何东西但是两个数字的 +1 或 -1 将打印出来。
using System;
namespace IsPrime
{
class MainClass
{
public static void Main (string[] args)
{
string isPlaying = "y";
bool isPrime;
while(isPlaying == "y")
{
var timer = System.Diagnostics.Stopwatch.StartNew ();
isPrime = isPrimeNum(9389274937501454911);
if (isPrime)
{
Console.WriteLine(9389274937501454911 + " is Prime");
}
else
Console.WriteLine(9389274937501454911 + " is not prime");
isPrime = isPrimeNum(7389274937501454911);
if (isPrime)
{
Console.WriteLine(7389274937501454911 + " is Prime");
}
else
Console.WriteLine(7389274937501454911 + " is not prime");
timer.Stop ();
var time = timer.ElapsedMilliseconds;
Console.WriteLine("Elasped Time: " + time + "\n");
Console.WriteLine("Do you want to play again?: y / n");
isPlaying = Console.ReadLine ();
}
}
static bool isPrimeNum(ulong n)
{
if (n == 1 || n == 2)
return true;
if (n % 2 == 0)
return false;
for(ulong i = 3; i < n; i = i + 2)
{
if (n % i == 0)
return false;
}
return true;
}
}
}