C#查找素数实现方法

本文所述为C#查找素数的程序代码,包括了可视化窗体的代码,找素数的方法可以借鉴。虽然实现的功能简单,不过为了演示一些C#技巧,本文实例中还用到了线程技术、ListBox列表框的使用、设置程序挂起等操作,其中备有详尽的注释,帮助大家更好的理解。

具体实现代码如下:

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Threading;
namespace SuspendAndResume
{
 public class Form1 : System.Windows.Forms.Form
 {
 private System.Windows.Forms.Label label1;
 private System.Windows.Forms.ListBox listBox1;
 private System.Windows.Forms.Button button1;
 private System.Windows.Forms.Button button2;
 private System.Windows.Forms.Button button3;
 private System.Windows.Forms.Button button4;
 private System.Windows.Forms.Label label2;
 private System.Windows.Forms.Timer timer1;
 private System.ComponentModel.IContainer components;
 //公共委托,用于输出素数
 public delegate void UD(string returnVal);
 //声明私有线程
 private Thread pNT;
 //用于标识是否挂起线程
 bool suspend = false;
 //用于标识线程时候开始运行
 bool pNTstart = false;
 public Form1()
 {
  InitializeComponent();
  // TODO: 在 InitializeComponent 调用后添加任何构造函数代码
 }
 protected override void Dispose( bool disposing )
 {
  if( disposing )
  {
  if (components != null)
  {
   components.Dispose();
  }
  }
  base.Dispose( disposing );
 }
 #region Windows 窗体设计器生成的代码
 private void InitializeComponent()
 {
  this.components = new System.ComponentModel.Container();
  this.label1 = new System.Windows.Forms.Label();
  this.listBox1 = new System.Windows.Forms.ListBox();
  this.button1 = new System.Windows.Forms.Button();
  this.button2 = new System.Windows.Forms.Button();
  this.button3 = new System.Windows.Forms.Button();
  this.button4 = new System.Windows.Forms.Button();
  this.label2 = new System.Windows.Forms.Label();
  this.timer1 = new System.Windows.Forms.Timer(this.components);
  this.SuspendLayout();
  // label1
  this.label1.Location = new System.Drawing.Point(8, 8);
  this.label1.Name = "label1";
  this.label1.TabIndex = 0;
  this.label1.Text = "已找到的素数:";
  // listBox1
  this.listBox1.ItemHeight = 12;
  this.listBox1.Location = new System.Drawing.Point(8, 32);
  this.listBox1.MultiColumn = true;
  this.listBox1.Name = "listBox1";
  this.listBox1.Size = new System.Drawing.Size(272, 136);
  this.listBox1.TabIndex = 1;
  // button1
  this.button1.Location = new System.Drawing.Point(19, 184);
  this.button1.Name = "button1";
  this.button1.Size = new System.Drawing.Size(48, 23);
  this.button1.TabIndex = 2;
  this.button1.Text = "创建";
  this.button1.Click += new System.EventHandler(this.button1_Click);
  //
  // button2
  //
  this.button2.Location = new System.Drawing.Point(88, 184);
  this.button2.Name = "button2";
  this.button2.Size = new System.Drawing.Size(48, 23);
  this.button2.TabIndex = 3;
  this.button2.Text = "挂起";
  this.button2.Click += new System.EventHandler(this.button2_Click);
  //
  // button3
  //
  this.button3.Location = new System.Drawing.Point(157, 184);
  this.button3.Name = "button3";
  this.button3.Size = new System.Drawing.Size(48, 23);
  this.button3.TabIndex = 4;
  this.button3.Text = "恢复";
  this.button3.Click += new System.EventHandler(this.button3_Click);
  //
  // button4
  //
  this.button4.Location = new System.Drawing.Point(226, 184);
  this.button4.Name = "button4";
  this.button4.Size = new System.Drawing.Size(48, 23);
  this.button4.TabIndex = 5;
  this.button4.Text = "销毁";
  this.button4.Click += new System.EventHandler(this.button4_Click);
  //
  // label2
  //
  this.label2.Location = new System.Drawing.Point(24, 224);
  this.label2.Name = "label2";
  this.label2.Size = new System.Drawing.Size(200, 23);
  this.label2.TabIndex = 6;
  this.label2.Text = "线程未启动";
  //
  // timer1
  //
  this.timer1.Enabled = true;
  this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
  //
  // Form1
  //
  this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
  this.ClientSize = new System.Drawing.Size(292, 266);
  this.Controls.Add(this.label2);
  this.Controls.Add(this.button4);
  this.Controls.Add(this.button3);
  this.Controls.Add(this.button2);
  this.Controls.Add(this.button1);
  this.Controls.Add(this.listBox1);
  this.Controls.Add(this.label1);
  this.Name = "Form1";
  this.Text = "素数";
  this.Load += new System.EventHandler(this.Form1_Load);
  this.ResumeLayout(false);
 }
 #endregion
 /// <summary>
 /// 应用程序的主入口点。
 /// </summary>
 [STAThread]
 static void Main()
 {
  Application.Run(new Form1());
 }
 private void button1_Click(object sender, System.EventArgs e)
 {
  //创建线程实例,设置属性
  pNT = new Thread(new ThreadStart(GPN));
  pNT.Name = "Prime Numbers Exaple";
  pNT.Priority = ThreadPriority.BelowNormal;
  //设置按键,停用开始按键,启用挂起按键和销毁按键
  button1.Enabled = false;
  button2.Enabled = true;
  button4.Enabled = true;
  //线程开始,并设置标识
  pNT.Start();
  pNTstart = true;
 }
 private void button2_Click(object sender, System.EventArgs e)
 {
  //设置挂起bool变量为真
  suspend = true;
  //设置按键,停用挂起按键, 启用恢复按键
  button2.Enabled = false;
  button3.Enabled = true;
 }
 private void button3_Click(object sender, System.EventArgs e)
 {
  //设置挂起bool变量为假
  suspend = false;
  //当线程当前状态为挂起时,恢复该线程
  if(pNT.ThreadState == System.Threading.ThreadState.Suspended
  || pNT.ThreadState == System.Threading.ThreadState.SuspendRequested)
  {
  try
  {
   //恢复线程
   pNT.Resume();
   //设置按键,停用恢复按键,启用挂起按键
   button3.Enabled = false;
   button2.Enabled = true;
  }
  catch(ThreadStateException Ex)
  {
   MessageBox.Show(Ex.ToString(), "提示");
  }
  }
 }
 private void button4_Click(object sender, System.EventArgs e)
 {
  //设置按键,启用开始按键,停用其他按键
  button1.Enabled = true;
  button2.Enabled = false;
  button3.Enabled = false;
  button4.Enabled = false;
  //销毁线程
  pNT.Abort();
 }
 //GPN为GetPrimeNumber的缩写,用于查找并显示素数
 public void GPN()
 {
  //声明变量
  long Counter;  //素数个数
  long NumberNow;  //当前数
  long SqrtOfNow;  //辅助数,做数组下标
  bool IsPrime = false; //标识是否为素数
  //数组,用于存储已找到素数
  long[] PrimeArray = new long[256];
  //委托,用于显示素数,即将其添加到ListBox中
  string[] args = new string[] {"2"};
  UD UIDel = new UD(UpdateUI);
  //初始化,从3开始计算,从第2个素数开始计算
  NumberNow = 3;
  Counter = 2;
  //添加2为素数,放入素数数组并将其显示
  PrimeArray[1] = 2;
  this.Invoke(UIDel, args);
  //循环,用于找到并输出256个素数
  while(Counter <= 255)
  {
  IsPrime = true;
  //从1到当前数的平方根,穷尽计算是否为素数
  for(SqrtOfNow = 1; (PrimeArray[SqrtOfNow]
   * PrimeArray[SqrtOfNow] <= NumberNow);
   SqrtOfNow++)
  {
   //若能被已找到的素数整除,则不是素数
   if(NumberNow % PrimeArray[SqrtOfNow] == 0)
   {
   //若不是素数,跳出for循环
   IsPrime = false;
   break;
   }
  }
  //若为素数,将其添加到ListBox以显示
  if(IsPrime)
  {
   //将素数存入数组中储存
   PrimeArray[Counter] = NumberNow;
   Counter++;
   //将素数显示到ListBox中
   args[0] = NumberNow.ToString();
   this.Invoke(UIDel,args);
   //利用bool变量,控制是否挂起线程
   if( suspend == true)
   {
   //调用Suspend方法,并捕捉异常
   try
   {
    pNT.Suspend();
   }
   catch(ThreadStateException Ex)
   {
    MessageBox.Show(Ex.ToString(), "提示");
   }
   }
   //使线程睡眠,使过程清楚显示,且有时间挂起线程
   Thread.Sleep(500);
  }
  //除2外,素数必为奇数,故跳过偶数的检查,优化算法
  NumberNow += 2;
  }
 }
 //更新ListBox的方法
 void UpdateUI(string result)
 {
  listBox1.Items.Add(result);
 }
 //利用Timer控件显示线程当前状态
 private void timer1_Tick(object sender, System.EventArgs e)
 {
  //在线程开时候再获取状态并显示
  if( pNTstart )
  {
  label2.Text = "线程当前状态是:" + pNT.ThreadState.ToString();
  }
 }
 private void Form1_Load(object sender, System.EventArgs e)
 {
  //设置按键,启用开始按键,停用其他按键
  button1.Enabled = true;
  button2.Enabled = false;
  button3.Enabled = false;
  button4.Enabled = false;
 }
 }
}

感兴趣的读者可以动手调试一下该程序代码,相信会有一定的启发与借鉴价值。

(0)

相关推荐

  • C#中查找Dictionary中重复值的方法

    简介 在这篇帮助文档中,我将向你展示如何实现c#里字典中重复值的查找.你知道的对于一个老鸟来说,这是非常简单的代码.但是尽管如此,这也是一篇对c#初学者非常有用的帮助文档. 背景 多数程序员对小型数据源存储的处理方式通常是创建字典进行键值存储.主键时唯一的,但是字典值却可能有重复的元素. 代码 这里我使用了一个简单的LINQ语句来查找字典中的重复值. 复制代码 代码如下: //initialize a dictionary with keys and values.    Dictionary<

  • C#查找列表中所有重复出现元素的方法

    本文实例讲述了C#查找列表中所有重复出现元素的方法.分享给大家供大家参考.具体实现方法如下: public T[] GetDuplicates(T inputValue) { List<T> duplicates = new List<T>( ); for (int i = 0; i < this.Count; i++) { if (this[i].Equals(inputValue)) { duplicates.Add(this[i]); } } return (dupli

  • C#二分查找算法实例分析

    本文实例讲述了C#二分查找算法.分享给大家供大家参考.具体实现方法如下: // input array is assumed to be sorted public int BinarySearch(int[] arr, int x) { if (arr.Length == 0) return -1; int mid = arr.Length / 2; if (arr[mid] == x) return mid; if (x < arr[mid]) return BinarySearch(Get

  • C#通过xpath查找xml指定元素的方法

    本文实例讲述了C#通过xpath查找xml指定元素的方法.分享给大家供大家参考.具体如下: orders.xml文档内容如下 <?xml version="1.0"?> <Order id="2004-01-30.195496"> <Client id="ROS-930252034"> <Name>Remarkable Office Supplies</Name> </Client

  • C# 递归查找树状目录实现方法

    1.递归查找树状目录 复制代码 代码如下: public partial class Form1 : Form    {        string path = @"F:\学习文件";//递归查找树状目录        public Form1()        {递归查找树状目录            InitializeComponent();        }        private void Form1_Load(object sender, EventArgs e) 

  • c# 二分查找算法

    折半搜索,也称二分查找算法.二分搜索,是一种在有序数组中查找某一特定元素的搜索算法. A 搜素过程从数组的中间元素开始,如果中间元素正好是要查找的元素,则搜素过程结束: B 如果某一特定元素大于或者小于中间元素,则在数组大于或小于中间元素的那一半中查找,而且跟开始一样从中间元素开始比较. C 如果在某一步骤数组为空,则代表找不到.这种搜索算法每一次比较都使搜索范围缩小一半. 时间复杂度折半搜索每次把搜索区域减少一半,时间复杂度为. (n代表集合中元素的个数)空间复杂度 复制代码 代码如下: //

  • C#查找字符串所有排列组合的方法

    本文实例讲述了C#查找字符串所有排列组合的方法.分享给大家供大家参考.具体实现方法如下: // 1. remove first char // 2. find permutations of the rest of chars // 3. Attach the first char to each of those permutations. // 3.1 for each permutation, move firstChar in all indexes // to produce even

  • C# 数组查找与排序实现代码

    1. 查找对象 复制代码 代码如下: Person p1 = new Person( " http://www.my400800.cn " , 18 ); Person p2 = new Person( " http://www.my400800.cn " , 19 ); Person p3 = new Person( " http://www.my400800.cn " , 20 ); Person[] persons = ... { p1,

  • C#中怎样从指定字符串中查找并替换字符串?

    using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;#region             #endregionnamespace Find{    public partial class Form

  • C#查找素数实现方法

    本文所述为C#查找素数的程序代码,包括了可视化窗体的代码,找素数的方法可以借鉴.虽然实现的功能简单,不过为了演示一些C#技巧,本文实例中还用到了线程技术.ListBox列表框的使用.设置程序挂起等操作,其中备有详尽的注释,帮助大家更好的理解. 具体实现代码如下: using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms;

  • Python实现求最大公约数及判断素数的方法

    本文实例讲述了Python实现求最大公约数及判断素数的方法.分享给大家供大家参考.具体实现方法如下: #!/usr/bin/env python def showMaxFactor(num): count = num / 2 while count > 1: if num % count == 0: print 'largest factor of %d is %d' % (num, count) break #break跳出时会跳出下面的else语句 count -= 1 else: prin

  • Java列出2到100之间所有素数的方法

    本文实例讲述了Java列出2到100之间所有素数的方法.分享给大家供大家参考.具体实现方法如下: //TestPrime.java: public class TestPrime { public static boolean isPrime(int num) { for(int i = 2; i <= Math.sqrt(num); i++) { //程序默认2是素数,当j=2时,循环不执行 if(num % i == 0) { return false; } } return true; }

  • 原生JS查找元素的方法(推荐)

    今天写了一个很简单.很粗暴的通过JS根据类来查找DOM元素. 为了降低它的粗暴等级(耗费性能)我给了三个等级. 首先性能最好的,适合FF,CH,IE8,通过querySelectorAll这个API. 其次是指定ID 最后只能全页面进行匹配class,不过比较节省的性能的是,在指定class名称的时候,同时传入HTML标签的类型,用于节省遍历的范围! 因为水平有限,目前也只能写成这种,真的好好奇JQ的选择器是怎么去匹配DOM的,如果有大神看到这篇文章,请不要吝啬施教... 下面贴代码: func

  • PHP使用反射机制实现查找类和方法的所在位置

    本文实例讲述了PHP使用反射机制实现查找类和方法的所在位置.分享给大家供大家参考,具体如下: //参数1是类名,参数2是方法名 $func = new ReflectionMethod('UnifiedOrder_pub', 'getPrepayId'); //从第几行开始 $start = $func->getStartLine() - 1; //从第几行结束 $end = $func->getEndLine() - 1; //获取路径地址 $filename = $func->get

  • Yii模型操作之criteria查找数据库的方法

    本文实例讲述了Yii模型操作之criteria查找数据库的方法.分享给大家供大家参考,具体如下: 数据模型搜索方法: public function search() { // Warning: Please modify the following code to remove attributes that // should not be searched. $criteria=new CDbCriteria; $criteria->compare('id',$this->id); $c

  • js查找节点的方法小结

    本文实例总结了js查找节点的方法.分享给大家供大家参考.具体分析如下: 这里介绍查找节点的三种方法: 1. 根据id查找,返回值为对象: 复制代码 代码如下: document.getElementById(); 2. 根据div/p/....等html标签查找,返回数组(实际也是对象) 复制代码 代码如下: document.getElementsByTagName(); 3. 在表单中使用,根据表单name来查找 复制代码 代码如下: document.getElementsByName()

  • Python3实现从指定路径查找文件的方法

    本文实例讲述了Python3实现从指定路径查找文件的方法.分享给大家供大家参考.具体实现方法如下: 这里给定一个搜索路径,根据这个路径请求和请求的文件名,找到第一个符合要求的文件 import os def search_file(file_name, search_path, pathsep = os.pathsep): for path in search_path.split(pathsep): candidate = os.path.join(path, file_name) if os

  • Go语言生成素数的方法

    本文实例讲述了Go语言生成素数的方法.分享给大家供大家参考.具体实现方法如下: 复制代码 代码如下: package main // 生成2, 3, 4, ... 到 channel 'ch'中. func Generate(ch chan<- int) {     for i := 2; ; i++ {         ch <- i  // Send 'i' to channel 'ch'.     } } // 从管道复制值 'in' 到 channel 'out', // 移除可整除的

  • PHP二分查找算法的实现方法示例

    本文实例讲述了PHP二分查找算法的实现方法.分享给大家供大家参考,具体如下: 二分查找法需要数组是一个有序的数组 假设我们的数组是一个递增的数组,首先我们需要找到数组的中间位置. 1. 要知道中间位置就需要知道起始位置和结束位置,然后取出中间位置的值来和我们的值做对比. 2. 如果中间值大于我们的给定值,说明我们的值在中间位置之前,此时需要再次二分,因为在中间之前,所以我们需要变的值是结束位置的值,此时结束位置的值应该是我们此时的中间位置. 3. 反之,如果中间值小于我们给定的值,那么说明给定值

随机推荐