YashasSamaga

Untitled

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