fork download
  1. #include <stdio.h>
  2. #include <math.h>
  3. #include <stdint.h>
  4.  
  5. #ifndef DBL_EPSILON
  6. #define DBL_EPSILON 2.2204460492503131e-16
  7. #endif
  8.  
  9. float power(float a, float b)
  10. {
  11. float res = 1;
  12.  
  13. for (int i = 0; i < b; ++i)
  14. {
  15. res *= a;
  16. }
  17.  
  18. return res;
  19. }
  20.  
  21. double root(int n, double x)
  22. {
  23. double d, r = 1;
  24. if (!x)
  25. {
  26. return 0;
  27. }
  28.  
  29. if (n < 1 || (x < 0 && !(n&1)))
  30. {
  31. return 0.0 / 0.0;
  32. }
  33.  
  34. do
  35. {
  36. d = (x / power(r, n - 1) - r) / n;
  37. r += d;
  38. } while (d >= DBL_EPSILON * 10 || d <= -DBL_EPSILON * 10);
  39.  
  40. return r;
  41. }
  42.  
  43.  
  44. long gcd(long a, long b)
  45. {
  46. return b == 0 ? a : gcd(b, a % b);
  47. }
  48.  
  49. void frac(float value, long* numerator, long* denominator)
  50. {
  51. double integral = floor(value);
  52. double frac = value - integral;
  53. const long precision = 1000000;
  54.  
  55. long commonDenominator = gcd(round(frac * precision), precision);
  56. *numerator = round(frac * precision) / commonDenominator;
  57. *denominator = precision / commonDenominator;
  58.  
  59. *numerator = *numerator + (integral * *denominator);
  60. }
  61.  
  62. int main() {
  63.  
  64. float base = 2;
  65. float exp = 2.5;
  66.  
  67.  
  68. printf("FIRST: %f\n", pow(base, exp));
  69.  
  70. //OR
  71.  
  72. //A ^ (B/C) is the same as CthRoot(A ^ B)
  73. long num = 0;
  74. long den = 0;
  75. frac(exp, &num, &den);
  76.  
  77. printf("SECOND: %f\n", root(den, power(base, num)));
  78.  
  79.  
  80. base = 3;
  81. exp = 2.7;
  82.  
  83. printf("THIRD: %f\n", pow(base, exp));
  84.  
  85. //OR:
  86.  
  87. num = 0;
  88. den = 0;
  89. frac(exp, &num, &den);
  90.  
  91. printf("FOURTH: %f\n", root(den, power(base, num)));
  92.  
  93. return 0;
  94. }
Success #stdin #stdout 0s 2168KB
stdin
Standard input is empty
stdout
FIRST: 5.656854
SECOND: 5.656854
THIRD: 19.419025
FOURTH: 19.419024