Advertisement
Guest User

Untitled

a guest
Dec 15th, 2014
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.31 KB | None | 0 0
  1. using MPI;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8.  
  9. namespace Lab7
  10. {
  11. static class MPrimes
  12. {
  13. static bool IsPrime(int n)
  14. {
  15. for (int i = 2; i <= Math.Sqrt(n); i++)
  16. if (n % i == 0) return false;
  17. return true;
  18. }
  19. public static ArrayList GetPrimes(int n, String[] args)
  20. {
  21. ArrayList result = new ArrayList();
  22. using (new MPI.Environment(ref args))
  23. {
  24. Intracommunicator comm = Communicator.world;
  25.  
  26. if(comm.Rank == 0)
  27. {
  28. int s = n / comm.Size;
  29. int t = s;
  30. for(int i = 1; i < comm.Size - 1; i++)
  31. {
  32. comm.Send<Tuple<int, int>>(new Tuple<int, int>(t + 1, t + s), i, 0);
  33. t += s;
  34. }
  35. if(comm.Size > 1) comm.Send<Tuple<int, int>>(new Tuple<int, int>(t + 1, n), comm.Size - 1, 0);
  36.  
  37. ArrayList temp = new ArrayList();
  38. for (int i = 2; i <= s; i++)
  39. {
  40. if (IsPrime(i)) temp.Add(i);
  41. }
  42.  
  43. comm.Barrier();
  44.  
  45. for (int i = 0; i < temp.Count; i++)
  46. Console.WriteLine(temp[i]);
  47.  
  48. ArrayList r;
  49. for (int i = 1; i < comm.Size; i++)
  50. {
  51. r = comm.Receive<ArrayList>(i, 0);
  52. for (int j = 0; j < r.Count; j++)
  53. result.Add(r[j]);
  54. }
  55. }
  56. else
  57. {
  58. ArrayList temp = new ArrayList();
  59. Tuple<int,int> t = comm.Receive<Tuple<int, int>>(0, 0);
  60. for(int i = t.Item1; i <= t.Item2; i++)
  61. {
  62. if (IsPrime(i)) temp.Add(i);
  63. }
  64. comm.Send<ArrayList>(temp, 0, 0);
  65. comm.Barrier();
  66.  
  67. }
  68.  
  69.  
  70. }
  71. return result;
  72. }
  73. }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement