Skip to content

Instantly share code, notes, and snippets.

@tnqsoft
Created April 27, 2017 22:40
Show Gist options
  • Save tnqsoft/7b3d942810b45a192717bad1d6d488dd to your computer and use it in GitHub Desktop.
Save tnqsoft/7b3d942810b45a192717bad1d6d488dd to your computer and use it in GitHub Desktop.
Code snippet with math lession
<?php
/**
* Code snippet with math lession
* @author Nguyen Nhu Tuan <tuanquynh0508@gmail.com>
*/
// 2^3 = 8
echo getExponential(2, 3);
echo '<br/>';
// 2 + 2^2 + 2^3
// = 2 + 4 + 8
// = 14
echo sumOfExponential(2, 3);
echo '<br/>';
// false
$str1 = 'abcba';
if (isSymmetryString($str1)) {
echo "'$str1' is symmetry <br/>";
} else {
echo "'$str1' is not symmetry <br/>";
}
// true
$str2 = 'abccba';
if (isSymmetryString($str2)) {
echo "'$str2' is symmetry <br/>";
} else {
echo "'$str2' is not symmetry <br/>";
}
#-------------------------------------------------------------------------------
/**
* Get Exponential
* Calculate Exponential expression
* Example: x^n like pow(x, n) function of php
* @author Nguyen Nhu Tuan <tuanquynh0508@gmail.com>
*
* @param integer $a
* @param integer $n
* @return integer
*/
function getExponential($a, $n)
{
if ($n === 1) {
return $a;
}
return $a * getExponential($a, $n-1);
}
/**
* Sum Of Exponential
* Calculate Sum Of Exponential expression
* Example: x + x^2 + x^3 + ... + x^n
* @author Nguyen Nhu Tuan <tuanquynh0508@gmail.com>
*
* @param integer $a
* @param integer $n
* @return integer
*/
function sumOfExponential($a, $n)
{
if ($n === 1) {
return $a;
}
return pow($a, $n) + sumOfExponential($a, $n-1);
}
/**
* Is Symmetry String
* Check string is symmetry or not
* Example: abcba is not symmetry, but abccba is symmetry
* @author Nguyen Nhu Tuan <tuanquynh0508@gmail.com>
*
* @param string $str
* @return boolean
*/
function isSymmetryString($str)
{
if (strlen($str) % 2 != 0) {
return false;
}
for ($i=0; $i < strlen($str)/2; $i++) {
if (substr($str, $i, 1) != substr($str, -($i+1), 1)) {
return false;
}
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment