[英]button that calc prime number in .net, c#
I need to write program that calculate prime numbers. 我需要编写计算素数的程序。 I searched online and found a code that do that but i am new at .net and having truble to know what to write in the Button1_Click function.
我在网上搜索并找到了执行此操作的代码,但是我是.net的新手,并且不知道要在Button1_Click函数中编写什么内容。 This is the code i took: http://www.dotnetperls.com/prime
这是我采用的代码: http : //www.dotnetperls.com/prime
This is the code i try to write to preform: 这是我尝试编写的代码:
namespace Test
{
public partial class TestWebForm : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
IsPrime prime = new IsPrime();
}
}
} }
i know this is not good question but i really need help. 我知道这不是一个好问题,但我确实需要帮助。 Thank you!
谢谢!
1) In the link you provided ,they already have a class which is static class which has the method IsPrime. 1)在您提供的链接中,它们已经有一个静态类,该类具有方法IsPrime。
2) you didn't include that class in your code. 2)您没有在代码中包含该类。 I did.
是的
3) In the button click event - I test to see if 7 is a prime number 3)在按钮单击事件中-我测试以查看7是否为质数
4) the result will be displayed in a blank page. 4)结果将显示在空白页中。 ( true or false).
( 对或错)。
namespace Test
{
public static class PrimeTool
{
public static bool IsPrime(int candidate)
{
// Test whether the parameter is a prime number.
if ((candidate & 1) == 0)
{
if (candidate == 2)
{
return true;
}
else
{
return false;
}
}
for (int i = 3;
(i * i) <= candidate; i += 2)
{
if ((candidate % i) == 0)
{
return false;
}
}
return candidate != 1;
}
}
public partial class TestWebForm: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
bool prime = PrimeTool.IsPrime(7); //when a class is static , you don't `new()` it.
Response.Write("7 is prime=" + prime);
}
}
}
Simply do it like this.
namespace Test
{
public partial class TestWebForm : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
int number = int.Parse(txtNumber.Text);
Response.Write(IsPrime(number));
}
private bool IsPrime(int number){
int boundary = Math.Floor(Math.Sqrt(number));
if (number == 1) return false;
if (number == 2) return true;
for (int i = 2; i <= boundary; ++i) {
if (number % i == 0) return false;
}
return true;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.