YashasSamaga

Untitled

Mar 18th, 2017
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.05 KB | None | 0 0
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <random>
  4. #include <cstdint>
  5. #include <cmath>
  6. /*****************************************************************************************/
  7. typedef std::uint_fast32_t random_num_type;
  8.  
  9. /*****************************************************************************************/
  10. // Wrapper for random number generator (RNG)
  11. /*****************************************************************************************/
  12. std::random_device seed_generator;
  13. std::mersenne_twister_engine <random_num_type,
  14.                               32, 624, 397, 31,
  15.                               0x9908b0df, 11,
  16.                               0xffffffff, 7,
  17.                               0x9d2c5680, 15,
  18.                               0xefc60000, 18, 1812433253> gen(seed_generator());
  19.  
  20. random_num_type generate_number()
  21. {
  22.     return gen();
  23. }
  24.  
  25. /*****************************************************************************************/
  26. // GCD Calculator (Euclid's Devision Lemma/Algorithm)
  27. /*****************************************************************************************/
  28. random_num_type gcd(random_num_type a, random_num_type b)
  29. {
  30.     return b == 0 ? a : gcd(b, a % b);
  31. }
  32.  
  33. /*****************************************************************************************/
  34. // GCD Calculator (Euclid's Devision Lemma/Algorithm)
  35. /*****************************************************************************************/
  36. int main()
  37. {
  38.     std::cout << std::setprecision(8);
  39.  
  40.     int count_coprime = 0, trials;
  41.     std::cout << "Enter the number of number pairs/number of trials to use: ";
  42.     std::cin >> trials;
  43.  
  44.     int trials_per_percent = trials / 100;
  45.    
  46.     for (int i = trials; i > 0; i--)
  47.     {
  48.         random_num_type a = generate_number();
  49.         random_num_type b = generate_number();
  50.         if (gcd(a, b) == 1) count_coprime++;
  51.  
  52.         if (i%trials_per_percent == 0) std::cout << ".";
  53.     }
  54.  
  55.     double pi = std::sqrt(static_cast<double>(6*trials)/count_coprime);
  56.  
  57.     std::cout << std::endl << "Out of " << trials << " pairs, " <<count_coprime<< "were co-prime pairs." << std::endl;
  58.     std::cout << "Approximate value of pi is: " << pi;
  59.     std::cin >> trials;
  60.     return 0;
  61. }
Add Comment
Please, Sign In to add comment