并行计算实现判断一个数是不是素数--Win32和.Net两种方式结合
程序员文章站
2024-01-05 18:15:34
// Win32D.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include
// Win32D.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <windows.h> #include <process.h> #include <math.h> #include <iostream> #include <fstream> using namespace std; int m; float c; int flag=0; int c2; HANDLE Thread1,Thread2; void StartThread1(LPVOID param) { for(int i=1;i<=m;i+=2) { if(flag==0) { if(c2%i==0&&i!=1) flag=1; } else break; } } void StartThread2(LPVOID param) { for(int j=2;j<=m;j+=2) { if(flag==0) { if(c2%j==0) flag=1; } else break; } } int _tmain(int argc, _TCHAR* argv[]) { cin>>c; m=sqrt(c); c2=(int)c; Thread1=CreateEvent(NULL,FALSE,FALSE,NULL); //cout<<"1"<<endl; Thread2=CreateEvent(NULL,FALSE,FALSE,NULL); //cout<<"2"<<endl; _beginthread(StartThread1,0,NULL); //cout<<"3"<<endl; _beginthread(StartThread2,0,NULL); //cout<<"4"<<endl; //WaitForSingleObject(Thread2,INFINITE); cout<<"5"<<endl; if(flag==0) cout<<"是素数"<<endl; else cout<<"不是素数"<<endl; cin>>c;//保留输出框 return 0; } /* .NET并行判断一个数是不是素数 */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace DotNetWyYt { class Program { public static int m; public static int c; public static int flag = 0; public static int c2; public static void WithDraw1() { for (int i = 1; i <= m; i += 2) { if (flag == 0) { if (c2 % i == 0 && i != 1) flag = 1; } else break; } } public static void WithDraw2() { for (int j = 2; j <= m; j += 2) { if (flag == 0) { if (c2 % j == 0) flag = 1; } else break; } } static void Main(string[] args) { c = 23; m = (Int32)Math.Sqrt((double)c); c2 = (int)c; ThreadStart thread1 = new ThreadStart(WithDraw1); Thread newThread1 = new Thread(thread1); ThreadStart thread2 = new ThreadStart(WithDraw2); Thread newThread2 = new Thread(thread2); newThread1.Start(); newThread2.Start(); if (flag == 0) Console.WriteLine("是素数"); else Console.WriteLine("不是素数"); } } }