Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <iomanip>
- #include <chrono>
- #include <cmath>
- #include <ctime>
- long double recursivePowImpl(long double x, int n) {
- if (n == 0) return 1.;
- return x * recursivePowImpl(x, n - 1);
- }
- long double recursivePow(long double x, int n) {
- if (n >= 0) {
- return recursivePowImpl(x, n);
- }
- return (1 / recursivePowImpl(x, std::fabs(n))); // fabs - берет модуль от числа
- }
- long double iterativePow(long double x, int n) {
- if (n == 0) return 1.;
- long double result = 1.;
- for (int i = 0; i < std::fabs(n); ++i) {
- result *= x;
- }
- if (n > 0) {
- return result;
- }
- return 1 / result;
- }
- int main()
- {
- setlocale(LC_ALL, "Russian");
- long double x;
- int n;
- std::cout << "Введите вещественное число для х: ";
- std::cin >> x;
- if (x == 0.) {
- std::cout << "х = 0. попробуйте другие числа" << std::endl;
- return 0;
- }
- std::cout << std::endl << "Введите целое число для n: ";
- std::cin >> n;
- std::cout << std::endl;
- auto start = std::chrono::high_resolution_clock::now();
- iterativePow(x, n);
- auto end = std::chrono::high_resolution_clock::now();
- double iterative_impl_time_taken =
- std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();
- iterative_impl_time_taken *= 1e-9;
- start = std::chrono::high_resolution_clock::now();
- recursivePow(x, n);
- end = std::chrono::high_resolution_clock::now();
- double recursive_impl_time_taken =
- std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();
- recursive_impl_time_taken *= 1e-9;
- std::cout << "время работалы итеративной программы : " << std::fixed << iterative_impl_time_taken
- << std::setprecision(9) << " секунд." << std::endl;
- std::cout << "время работалы рекурсивной программы : " << std::fixed << iterative_impl_time_taken
- << std::setprecision(9) << " секунд." << std::endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment