Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <math.h>
- using namespace std;
- int In(const char* t)
- {
- int x;
- cout << t << endl;
- while (!(cin >> x) || cin.peek() != '\n')
- {
- cin.clear();
- cout << "ERROR" << endl;
- while (cin.get() != '\n');
- }
- return x;
- }
- int N(const char* t)
- {
- int x;
- do
- {
- x = In(t);
- } while (x < 0);
- return x;
- }
- double fun(int x, int n)
- {
- if (n % 2 == 0)
- {
- return pow(pow(x, n / 2), 2);
- }
- else
- {
- return x * pow(x, n - 1);
- }
- }
- int rec(int x, int n)
- {
- if (n == 0)
- {
- return 1;
- }
- if (n % 2 == 1)
- {
- return rec(x, n - 1) * x;
- }
- else
- {
- int b = rec(x, n / 2);
- return b * b;
- }
- }
- int main()
- {
- setlocale(LC_ALL, "Rus");
- cout << "Задание: Вычислить y=x^n по следующему правилу: y=(x^n/2)^2, если n чётное, и y=x*y^n-1, если n нечётное." << endl;
- int n;
- double x, y;
- x = In("Введите значение X: ");
- n = N("Введите степень n: ");
- y = pow(x, n);
- cout << "Результат y=x^n: " << y << endl << "Следующий результат будет получен согласно условию задания" << endl;
- cout << "Ответ — " << fun(x, n) << endl;
- cout << "Рекурсия — " << rec(x, n) << endl;
- system("pause");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement