The example in this article describes how to find the number of palindromes in a specified range in php and the square root is also a palindrome. Literary and numerical methods. Share it with everyone for your reference. The details are as follows:
1. Requirements:
Given two values X and Y, count the number of palindromes in this interval, and require that their square roots are also palindromes. where 1<= x <= y < 10 14
2. Solution:
<?php error_reporting(E_ALL); ini_set("display_errors", 1); //避免超时 set_time_limit(0); $t1=microtime(); function isPlalindrome($num){ $str="$num"; $len=strlen($num); $k = intval($len/2) + 1;//获取中间位数 for($j=0;$j<$k;$j++){ if($str{$j}!=$str{$len-1-$j}){ return false; } } return true; } function showPlalindrome($min,$max){ //因为要计算在$min,$max间的回文数且其自身平方根也是回文数 //所以相当于求一sqrt($min)~sqrt($max)间数 //其平方在$min~$max间也是回文数 //$min~$max是连续正整数,所以可以这样缩小很多计算量,否则…… $start=sqrt($min); $end=sqrt($max); for($i=$start;$i<$end;$i++){ if(isPlalindrome($i) &&isPlalindrome($n=$i*$i) ){ echo $n." <br/>"; } } } showPlalindrome(1,100000000000000); $t2=microtime(); $starttime = explode(" ",$t1); $endtime = explode(" ",$t2); $totaltime = $endtime[0]-$starttime[0]+$endtime[1]-$starttime[1]; $timecost = sprintf("%s",$totaltime); echo "页面运行时间: $timecost 秒"; ?>
I hope this article will be helpful to everyone’s PHP programming design.