First than nothing I'm not a native guy so sorry for all those mistakes.
I'm trying to get the largest palindromic product between two integers, for example; 3 and 11, the largest will be 11*11=121.
I tried with this.
function Pallendrome($str) : bool {
return (strval($str) == strrev(strval($str))) ? true : false;
}
function largestPalindromicProduct($lower, $upper) {
$array = array();
for($it=$upper; $it >= $lower; $it--){
for($it_=$upper; $it_ >= $lower; $it_--){
$num = $it*$it_;
if(Pallendrome($num)) { array_push($array, $num); }
}
}
if(empty($array)) { return NAN; }
else{ ksort($array); return $array[0];}
}
But, I'd need to get a way to optimize it 'cause it's taking a long time due to the numbers introduced in, are kind of big.
Do you guys have some idea for it? Thank ya!.
I'm sure the folks over at math.stackexchange.com could help you with a better algorithm, but for the purposes of optimizing what you've got thus far, here's a summation of all my comments:
function largestPalindromicProduct($lower, $upper)
{
$largest = 0;
for ($it = $upper; $it >= $lower; $it--) {
for ($it_ = $upper; $it_ >= $lower; $it_--) {
$num = $it * $it_;
// If we're on the first iteration and we have a product lower than the
// largest we've found so far, then we know we can never get a larger
// number (because we're counting down) and we can abort immediately.
if ($num <= $largest) {
if ($it_ == $upper) {
break 2;
}
// Otherwise, we can at least abort the rest of this subloop.
break;
}
// Only check if it's a palindrome once we've passed all the other checks.
if ($num == strrev($num)) {
$largest = $num;
}
}
}
return $largest;
}
im trying to create a script that generates a number and depending on the number generated it prints something specific but it's not working properly, Heres the code:
<?php
for($zz = 1; $zz <= 20; $zz++) {
$rangen = rand(1,100);
$a = (1 <= 0) && (0 <= 7);
$b = (8 <= 0) && (0 <= 17);
echo ("<br>".$rangen . "<br>");
if($a) {
echo "a";
} elseif ($b) {
echo "b";
} else {
echo "c";
}
}
?>
The error is that it keeps printing "c" no matter what the number is.
If anyone could help that would be great, thanks.
Your conditions are all wrong. Your comparing the same numbers and never using $rangen, this is why you obtain the same result each time.
1 <= 0 and 8 <= 0 will always return false which is why you always go to the else statement.
I tried to find For a given positive integer Z, check if Z can be written as PQ, where P and Q are positive integers greater than 1. If Z can be written as PQ, return 1, else return 0
I tried lots with online solution,
Check if one integer is an integer power of another
Finding if a number is a power of 2
but it's not what i need , any hint or any tips?
Here's the naive method - try every combination:
function check($z) {
for($p = 2; $p < sqrt($z); $p++) {
if($z % $p > 0) {
continue;
}
$q = $p;
for($i = 1; $q < $z; $i++) {
$q *= $p;
}
if($q == $z) {
//print "$z = $p^$i";
return 1;
}
}
return 0;
}
Similarly, using php's built in log function. But it may not be as accurate (if there are rounding errors, false positives may occur).
function check($z) {
for($p = 2; $p < sqrt($z); $p++) {
$q = log($z,$p);
if($q == round($q)) {
return 1;
}
}
return 0;
}
I'm pretty new to PHP, especially object oriented php, and I'm working on some simple code, and I'm not quite sure what's wrong with what I've written so far. I'm sure it's something simple but I've beat my head against this wall for a little bit, figured I'd ask here.
class primes
{
$TestValues = array(0, 1, 2, 3, 4);
function IsPrime($number)
{
//if number is a number, perform the rest of the tests, else, return -1 (error)
if(is_numeric($number))
{
//if number is less than 0, return -1 (error)
if($number < 0)
return -1;
//if number is 0, then return 0 (false, not prime)
if($number == 0)
return 0;
//if number is greater than 1024, return -1 (error)
if($number > 1024)
return -1;
//if number is 1, return 0 (false, not prime)
if($number == 1)
return 0;
//if number is 2, return 1 (true, is prime)
if($number == 2)
return 1;
//if number mod 2 is 0, then it is even, and no even number is prime except 2, which is handled above. so return 0 (false, not prime)
if($number % 2 == 0)
return 0;
//if number has passed all previous tests, mod it by all odd numbers from 3 to its square root rounded up.
for($i = 3; $i <= ceil(sqrt($number)); $i = $i +2)
{
//if any numbers mod 3 to its square root equal 0, return 0, (false, not prime)
if($number % $i == 0)
return 0;
}
//if the number has passed all above requirements, then it is a prime number below 1024.
return 1;
else
{
return -1;
}
}
}
function TestIsPrime()
{
foreach($TestValues as $value)
IsPrime($value);
if(IsPrime() == 0)
echo($value . "=> Is not Prime");
elseif(IsPrime() == 1)
echo($value . "=> Is Prime");
elseif(IsPrime() == -1)
echo($value . "=> Is an Error");
}
function main()
{
TestIsPrime();
}
}
main();
I'm getting an error saying I don't place my array where it is currently. I'm not quite sure how the structure of php code is supposed to work with a class, so I wasn't sure where to put the $TestValues array, so I tried a few places, and none would be accepted. Also, I'm getting an error on the else statement connected to the first if(is_numeric($number)), but I couldn't be sure that the error wasn't caused by another small error I was getting. The last error is that I'm not sure where in this single page of code to call the functions inside the class. Any help would be appreciated. Once again, I'm new to doing anything useful in php, but I'm liking it so far. Thanks,
Your code was missing several braces, also you your $TestValues is part of the class, not a global variable.
I fixed the code, however you have to check the math and read the oop tutorial on php's site.
<?php
class Primes {
public $TestValues = array(0, 1, 2, 3, 4);
function IsPrime($number) {
//if number is a number, perform the rest of the tests, else, return -1 (error)
if(is_numeric($number)) {
if($number < 0 || $number > 1024)
return -1;
if($number === 0 || $number === 1 || $number % 2 === 0)
return 0;
//if number has passed all previous tests, mod it by all odd numbers from 3 to its square root rounded up.
for($i = 3; $i <= ceil(sqrt($number)); $i = $i + 2) {
//if any numbers mod 3 to its square root equal 0, return 0, (false, not prime)
if($number % $i == 0)
return 0;
}
//if the number has passed all above requirements, then it is a prime number below 1024.
return 1;
} else {
return -1;
}
}
function test() {
foreach($this->TestValues as $value) {
$t = $this->IsPrime($value);
if($t === 0) {
echo($value . "=> Is not Prime");
} elseif($t === 1) {
echo($value . "=> Is Prime");
} elseif(IsPrime() == -1) {
echo($value . "=> Is an Error");
}
echo "\n";
}
}
}
function main() {
$prime = new Primes();
$prime->test();
}
main();
You have some syntax errors in your code. I made some modification to your code now it is working :
<?php
// Check the number to be prime or not
function IsPrime($number)
{
// If the variable is not numeric, negative or greater than 1024, exit
if (!is_numeric($number) || $number < 0 || $number > 1024)
{
return -1;
}
// Perform the tests
switch($number)
{
//if number is 0 or 1, then return 0 (false, not prime)
case 0 :
case 1 :
return 0;
break;
//if number is 2, return 1 (true, is prime)
case 2 :
return 1;
break;
}
//if number mod 2 is 0, then it is even, and no even number is prime except 2, return 0 (false, not prime)
if($number % 2 == 0)
{
return 0;
}
//if number has passed all previous tests, mod it by all odd numbers from 3 to its square root rounded up.
for($i = 3; $i <= ceil(sqrt($number)); $i = $i +2)
{
if($number % $i == 0)
{
return 0;
}
}
//if the number has passed all above requirements, then it is a prime number below 1024.
return 1;
} // End of isprime function
// create an array of numbers
$testvalues = range(-2, 100);
foreach($testvalues as $value)
{
switch(isprime($value))
{
case 0 :
echo("<p style='color:gainsboro;'>" . $value . "=> Is not Prime</p>");
break;
case 1 :
echo("<p style='color:green;'>" . $value . "=> Is Prime</p>");
break;
case -1 :
echo("<p style='color:red;'>" . $value . "=> Is an Error</p>");
break;
}
}
?>
Notes :
I think you don't need a class here. It is a simple program and using
classes will make it a bit complex and php is known for its
simplicity. So keep it simple.
In some cases switch is better and more readable than if, so use it if
possible http://php.net/manual/en/control-structures.switch.php
Every language has it preferred syntax. In php it is common not to
use capitals in naming variable (except for classes) unlike other
languages
there is no main() in php
Hope this helps, excuse my english and correct me if I am wrong
The reason why u getting error for else statement is because of the closing braces } of your if statement, notice that you have a closing brace after your else condition,instead of doing that, you have to close if statement first then do else statement which in your case else means if is not numeric then do sth, also you have so many if statements which looks a little bit redundant. what you could do is to put them in same condition like if($number ==0 || $number == 2 || $number % 2 ==0 ) return 0 elseif // do sth
The reason why you can't get $Testvalues is that you need to pass the array to your function then you can use it, where did u call your TestIsPrime function? when you call it, do sth like
TestIsPrime($TestValues);
btw, it's better not to use Capital letter for variable...
I got the answer fine, but when I run the following code,
$total = 0;
$x = 0;
for ($i = 1;; $i++)
{
$x = fib($i);
if ($x >= 4000000)
break;
else if ($x % 2 == 0)
$total += $x;
print("fib($i) = ");
print($x);
print(", total = $total");
}
function fib($n)
{
if ($n == 0)
return 0;
else if ($n == 1)
return 1;
else
return fib($n-1) + fib($n-2);
}
I get the warning that I have exceeded the maximum execution time of 30 seconds. Could you give me some pointers on how to improve this algorithm, or pointers on the code itself? The problem is presented here, by the way.
Let's say $i equal to 13. Then $x = fib(13)
Now in the next iteration, $i is equal to 14, and $x = fib(14)
Now, in the next iteration, $i = 15, so we must calculate $x. And $x must be equal to fib(15). Now, wat would be the cheapest way to calculate $x?
(I'm trying not to give the answer away, since that would ruin the puzzle)
Try this, add caching in fib
<?
$total = 0;
$x = 0;
for ($i = 1;; $i++) {
$x = fib($i);
if ($x >= 4000000) break;
else if ($x % 2 == 0) $total += $x;
print("fib($i) = ");
print($x);
print(", total = $total\n");
}
function fib($n) {
static $cache = array();
if (isset($cache[$n])) return $cache[$n];
if ($n == 0) return 0;
else if ($n == 1) return 1;
else {
$ret = fib($n-1) + fib($n-2);
$cache[$n] = $ret;
return $ret;
}
}
Time:
real 0m0.049s
user 0m0.027s
sys 0m0.013s
You'd be better served storing the running total and printing it at the end of your algorithm.
You could also streamline your fib($n) function like this:
function fib($n)
{
if($n>1)
return fib($n-1) + fib($n-2);
else
return 0;
}
That would reduce the number of conditions you'd need to go through considerably.
** Edited now that I re-read the question **
If you really want to print as you go, use the output buffer. at the start use:
ob_start();
and after all execution, use
ob_flush();
flush();
also you can increase your timeout with
set_time_limit(300); //the value is seconds... so this is 5 minutes.