Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream> // подключение библиотеки
- #include <chrono>
- class Timer //класс для времени
- {
- public:
- Timer() // конструктор
- : start_(std::chrono::high_resolution_clock::now())
- {
- }
- ~Timer() // деструктор с выводом времени
- {
- const auto finish = std::chrono::high_resolution_clock::now();
- std::cout << std::chrono::duration_cast<std::chrono::microseconds>(finish - start_).count() << " us" << std::endl;
- }
- private:
- const std::chrono::high_resolution_clock::time_point start_;
- };
- void Pi(int n, int** pi) // объявление функции
- {
- Timer t; // инициализация таймера
- int length = 10 * n / 3 + 1, cnt_9 = 0, count_oper = 0; // объявление переменных
- // length необходимая длина временного массива
- // cnt_9 счетчик 9-ок
- int dgt = 0, *data, j;
- data = new int[length]; // создание временного массива
- for (int i = 0; i < length; i++) // заполнение массива 2-ками
- data[i] = 2;
- for (j = 0; j < n; j++) // запуск цикла, зависящего от необходимого количества цифр
- {
- int tmp = 0;
- for (int i = length; i > 0; i--) // запуск цикла в обратную сторону
- {
- int x = 10 * data[i-1] + tmp*i; // формулы
- count_oper += 2;
- data[i-1] = x % (2*i - 1);
- count_oper += 3;
- tmp = x / (2*i - 1);
- count_oper += 3;
- }
- data[0] = tmp % 10;
- tmp /= 10;
- count_oper += 2;
- if (tmp == 9) cnt_9++; // увеличение счетчика
- else if (tmp == 10) // если цифра оказалась равной 10
- {
- *(*(pi)+j) = dgt + 1; // вывод цифры на 1 больше
- for (int i = 0; i < cnt_9; i++) // выводим 0
- *(*(pi)+j) = 0; // *(*(pi)+j) ~ pi[j] необходимо, так как массив передан по ссылке
- dgt = 0;
- cnt_9 = 0;
- }
- else
- {
- //вывод очередной цифры
- *(*(pi)+j) = dgt;
- dgt = tmp;
- if (cnt_9 != 0) // вывод 9-ок
- for (int i = 0; i < cnt_9; i++)
- *(*(pi)+j) = 9;
- cnt_9 = 0;
- }
- if (j == 10 || j == 100 || j == 1000 || j == 10000) // вывод значений
- {
- std::cout << "N = " << n << " j = " << j << " operations = " << count_oper << " time = ";
- t.~Timer();
- }
- }
- *(*(pi)+j) = dgt; // вывод последней цифры
- std::cout << "Total time: ";
- }
- int main()
- {
- int N = 1000, *pi;
- pi = new int[N+1]; // создание массива для хранения цифр
- Pi(N, &pi); // запуск функции
- std::cout << "pi = ";
- for (int i = 1; i <= N; i++)
- {
- std::cout << pi[i];
- if (i == 1) std::cout << ","; // для красивого вывода
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement