Advertisement
Guest User

11

a guest
Feb 29th, 2020
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. #include <iostream>
  2. #include <math.h>
  3.  
  4. using namespace std;
  5.  
  6. int In(const char* t)
  7. {
  8. int x;
  9. cout << t << endl;
  10. while (!(cin >> x) || cin.peek() != '\n')
  11. {
  12. cin.clear();
  13. cout << "ERROR" << endl;
  14. while (cin.get() != '\n');
  15. }
  16. return x;
  17. }
  18.  
  19. int N(const char* t)
  20. {
  21. int x;
  22. do
  23. {
  24. x = In(t);
  25. } while (x < 0);
  26. return x;
  27. }
  28. double fun(int x, int n)
  29. {
  30. if (n % 2 == 0)
  31. {
  32. return pow(pow(x, n / 2), 2);
  33. }
  34. else
  35. {
  36. return x * pow(x, n - 1);
  37. }
  38. }
  39. int rec(int x, int n)
  40. {
  41. if (n == 0)
  42. {
  43. return 1;
  44. }
  45. if (n % 2 == 1)
  46. {
  47. return rec(x, n - 1) * x;
  48. }
  49. else
  50. {
  51. int b = rec(x, n / 2);
  52. return b * b;
  53. }
  54. }
  55.  
  56. int main()
  57. {
  58. setlocale(LC_ALL, "Rus");
  59. cout << "Задание: Вычислить y=x^n по следующему правилу: y=(x^n/2)^2, если n чётное, и y=x*y^n-1, если n нечётное." << endl;
  60. int n;
  61. double x, y;
  62.  
  63. x = In("Введите значение X: ");
  64. n = N("Введите степень n: ");
  65. y = pow(x, n);
  66. cout << "Результат y=x^n: " << y << endl << "Следующий результат будет получен согласно условию задания" << endl;
  67. cout << "Ответ — " << fun(x, n) << endl;
  68. cout << "Рекурсия — " << rec(x, n) << endl;
  69. system("pause");
  70. return 0;
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement