Advertisement
Guest User

Untitled

a guest
Aug 22nd, 2017
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.16 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <math.h>
  3. #include "PrimalityChecker.decl.h"
  4.  
  5. struct Number
  6. {
  7. long Value;
  8. bool IsPrime;
  9. };
  10.  
  11. class Main : public CBase_Main
  12. {
  13. private:
  14.  
  15. int count;
  16. int k;
  17. Number *numbers;
  18.  
  19. public:
  20.  
  21. Main(CkArgMsg *msg)
  22. {
  23. // To avoid generating the same random numbers.
  24. srand(time(0));
  25.  
  26. if (msg->argc < 1)
  27. {
  28. ckout<<"Expecting one argument.";
  29. CkAbort("");
  30. }
  31.  
  32. k = atoi(msg->argv[1]);
  33. count = k;
  34. numbers = new Number[k];
  35.  
  36. for (int i=0; i<k; i++)
  37. {
  38. numbers[i].Value = rand();
  39. CProxy_CheckPrimality::ckNew(thisProxy, numbers[i].Value, i);
  40. }
  41. }
  42.  
  43. void Done(int index, bool result)
  44. {
  45. count--;
  46. numbers[index].IsPrime = result;
  47.  
  48. if (count == 0)
  49. {
  50. for (int i=0; i<k; i++)
  51. {
  52. ckout<<i+1<<"; Number: "<<numbers[i].Value<<"; IsPrime: "<<numbers[i].IsPrime<<endl;
  53. }
  54.  
  55. CkExit();
  56. }
  57. }
  58. };
  59.  
  60. class CheckPrimality : public CBase_CheckPrimality
  61. {
  62. private:
  63.  
  64. const long number;
  65.  
  66. bool isPrime()
  67. {
  68. // If the number is smaller than 1 or is even then it cannot be a prime.
  69. if (number <= 1 || number&1 == 0)
  70. {
  71. return false;
  72. }
  73.  
  74. // Checking only till square root of the number since one of the factor
  75. // will be either less than or equal to the sqaure root.
  76. for (int i=2; i*i<=number; i++)
  77. {
  78. if (number%i == 0)
  79. {
  80. return false;
  81. }
  82. }
  83.  
  84. return true;
  85. }
  86.  
  87. public:
  88.  
  89. CheckPrimality(CProxy_Main mainProxy, const long _number, const int index) : number(_number)
  90. {
  91. bool isPrimeResult = isPrime();
  92. mainProxy.Done(index, isPrimeResult);
  93. }
  94. };
  95.  
  96. #include "PrimalityChecker.def.h"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement