Advertisement
Guest User

Untitled

a guest
Apr 27th, 2017
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4. * Code snippet with math lession
  5. * @author Nguyen Nhu Tuan <tuanquynh0508@gmail.com>
  6. */
  7.  
  8. // 2^3 = 8
  9. echo getExponential(2, 3);
  10. echo '<br/>';
  11.  
  12. // 2 + 2^2 + 2^3
  13. // = 2 + 4 + 8
  14. // = 14
  15. echo sumOfExponential(2, 3);
  16. echo '<br/>';
  17.  
  18. // false
  19. $str1 = 'abcba';
  20. if (isSymmetryString($str1)) {
  21. echo "'$str1' is symmetry <br/>";
  22. } else {
  23. echo "'$str1' is not symmetry <br/>";
  24. }
  25.  
  26. // true
  27. $str2 = 'abccba';
  28. if (isSymmetryString($str2)) {
  29. echo "'$str2' is symmetry <br/>";
  30. } else {
  31. echo "'$str2' is not symmetry <br/>";
  32. }
  33.  
  34. #-------------------------------------------------------------------------------
  35. /**
  36. * Get Exponential
  37. * Calculate Exponential expression
  38. * Example: x^n like pow(x, n) function of php
  39. * @author Nguyen Nhu Tuan <tuanquynh0508@gmail.com>
  40. *
  41. * @param integer $a
  42. * @param integer $n
  43. * @return integer
  44. */
  45. function getExponential($a, $n)
  46. {
  47. if ($n === 1) {
  48. return $a;
  49. }
  50.  
  51. return $a * getExponential($a, $n-1);
  52. }
  53.  
  54. /**
  55. * Sum Of Exponential
  56. * Calculate Sum Of Exponential expression
  57. * Example: x + x^2 + x^3 + ... + x^n
  58. * @author Nguyen Nhu Tuan <tuanquynh0508@gmail.com>
  59. *
  60. * @param integer $a
  61. * @param integer $n
  62. * @return integer
  63. */
  64. function sumOfExponential($a, $n)
  65. {
  66. if ($n === 1) {
  67. return $a;
  68. }
  69.  
  70. return pow($a, $n) + sumOfExponential($a, $n-1);
  71. }
  72.  
  73. /**
  74. * Is Symmetry String
  75. * Check string is symmetry or not
  76. * Example: abcba is not symmetry, but abccba is symmetry
  77. * @author Nguyen Nhu Tuan <tuanquynh0508@gmail.com>
  78. *
  79. * @param string $str
  80. * @return boolean
  81. */
  82. function isSymmetryString($str)
  83. {
  84. if (strlen($str) % 2 != 0) {
  85. return false;
  86. }
  87.  
  88. for ($i=0; $i < strlen($str)/2; $i++) {
  89. if (substr($str, $i, 1) != substr($str, -($i+1), 1)) {
  90. return false;
  91. }
  92. }
  93.  
  94. return true;
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement