How to check if a given number is Fibonacci number? - php

i am trying to check my numbers is fibonacii or not ?
isFibonacci(13);
function isFibonacci( $testedNumber, $a = 1, $b = 1 )
{
if( $testedNumber == 0 || $testedNumber == 1 )
return true;//returning true for 0 and 1 right away.
$nextFib = $a + $b;//getting the next number in the sequence
if( $nextFib > $testedNumber )
return false;//if we have passed the tested number, it's not in the sequence
else if( $nextFib == $testedNumber )
return true;//if we have a perfect match, the tested number is in the sequence
else
isFibonacci( $testedNumber, $b, $nextFib );//otherwise, get the next fibonacci number and repeat.
}

<?php
function getFibonicciIndex($number)
{
$log_base = (1+sqrt(5))/2;
$index = log(($number*sqrt(5)-(1/2)), $log_base);
return floor($index)+1;
}
function getFibonicciNumber($term)
{
$a = (1+sqrt(5))/2;
$b = (1-sqrt(5))/2;
$fibonicci_number = (pow($a, $term)-pow($b, $term))/sqrt(5);
return $fibonicci_number;
}
$number = 14;
$index = getFibonicciIndex($number);
$index_value = getFibonicciNumber($index);
echo ($number == $index_value) ? "yes" : "no";
//This logic implements the best rule to find the Fibonacci series and their index. First we suppose the given no. is a part of Fibonacci series and try to get index .. and then for that given index we calculate the Fibonacci number and equate it to verify

Related

how Searching the database for similar numbers?

What is the way to search the database (mysql/php code) for the following entries:
123XX
123XY
XYZ44
1X344
1Z344
Z23YY
The input letters are only X - Y - Z and the numbers from 0 to 9
They are all one number, which is (12344), so how can I show these results? The goal is to search for repeated entries.
Another example :
12XYY
X = 3,4,5,6,7,8,9,0
Y = 3,4,5,6,7,8,9,0
Provided that y is not equal to x or any apparent number (1,2)
And X is not equal to Y or any apparent number (1,2)
$number = "1XZYY";
$rnumber = str_replace(array('Y','X','Z'), "ـ", $number);
$lenNumber = strlen(5);
$duplicate = $mysqli->query("SELECT `number` FROM `listNumber` WHERE (length(`number`) = '$lenNumber' && `number` LIKE '%$rnumber%') OR (length(`number`) = '$lenNumber' && `number`LIKE '%$rnumber%')");
I tried many methods, but it was very slow in showing the results because I put the loop inside a loop to search for every number in the first loop
I understand you want to look for 12344, but some of the digits may be been redacted and replaced with a random capital letter in XYZ. For that, you can use a regular expression:
WHERE REGEXP_LIKE(foo, '^[XYZ1][XYZ2][XYZ3][XYZ4][XYZ4]$')
Demo
I would use PHP and occupy each digit into the correct position until I find a conflict. To prevent a double loop I use a dictionary helper object to hold values of X, Y and Z.
function match_str_to_number($str, $number)
{
if (strlen($number) != strlen($str)) {
return false;
}
$dict = ['X' => -1, 'Y' => -1, 'Z' => -1];
for ($i = 0; $i < strlen($number); $i++) {
if ($number[$i] != $str[$i]) {
// a number mismatch
if (!isset($dict[$str[$i]])) {
return false;
}
// a wildcard variable conflict
if ($dict[$str[$i]] != $number[$i] && $dict[$str[$i]] != -1) {
return false;
};
$dict[$str[$i]] = $number[$i];
}
}
return true;
}
echo match_str_to_number("XYZ44", "12344") ? "true" : "false";
echo match_str_to_number("XYZ4X", "12344") ? "true" : "false";
// output: truefalse

PHP strcmp result int meaning

In php, there is a built-in function strcmp to compare if two strings are same or not.
Returning value is integer number that if the first parameter is greater than the second I get > 0, if not < 0 and if the same 0.
So the part I don't get is comparing string as number.
Does PHP convert string to number and if so how's PHP converting?
$a = 'acorn';
$b = 'zebra';
var_dump( strcmp($a, $b) ); // -25 <- what's this number? seems like alphabetical position...nnn
Doesn't it really matter what number I get, shall I just take what it is?
Looking at the PHP: strcmp doc :
Returns < 0 if str1 is less than str2; > 0 if str1 is greater than
str2, and 0 if they are equal.
So yes, you can use it as it is to compare your string.
But if you want to understand the number returned by the function, it depend on the characters that makes the strings.
In ASCII :
A=65 < B=66 < C=67 ....
So if the string are different, one is gonna be greater than the other.
So you can also test it easily with a short script :
<?php
$a='A';
$b='B';
$c='C';
//Return -1 because $a is smaller than $b by one (65 < 66 )
echo strcmp($a,$b);
//Return -2 because $a is smaller than $c by two (65 < 67 )
echo strcmp($a,$c);
//Return -1 because $b is smaller than $c by one (66 < 67 )
echo strcmp($b,$c);
//Return 1 because $c is greater than $b by one (67 > 66 )
echo strcmp($c,$b);
//Return 2 because $c is greater than $a by two (67 > 65 )
echo strcmp($c,$a);
strcmp is using for comparing two strings in PHP.
If your result is greater the 0 its mean variable one ($a) is greater then Var2($b)
if return result is less then 0 its mean $b is greater and If result is equal to 0 its mean both strings are equal to each other.
$a="Hello world!";
$b= "Hello world!";
var_dump(strcmp($a, $b)); // result is 0
$a = "Hello";
$b = "Hello World";
var_dump(strcmp($a, $b)); // Outputs: -6
and If you want to see difference then you can use this
$a = 'some-content-here-example';
$b = 'some-content-example';
$asp = preg_split('//', $a, -1);
$bsp = preg_split('//', $b, -1);
$l1 = count($asp);
$l2 = count($bsp);
$length = $l1;
if ($l2 > $l1) {
$length = $l2;
}
$record = null;
$x = null;
for ($x = 0; $x < $length; $x++) {
if ($a[$x] != $b[$x]) {
if (!isset($a[$x])) {
$record.= $b[$x];
} else {
$record.= $a[$x];
}
}
}
echo $record;

Algorithm to find positive and negative integer square roots (without given boundaries)

I've been practicing a lot of algorithms recently for an interview. I was wondering if there was another way to solve this problem. I wrote it in a way where I only increment it positively, because I know from basic math that two negatives multiplied by each other would result to a positive number, so I would just have to make the integer that would satisfy the condition to negative.
Is there a way to write this elegantly where you didn't have the knowledge of multiplying two negative numbers result to a positive?
<?php
# Z = {integers}
# B = {x:x, x is an element of Z, x^2 + 1 = 10}
$numNotFound = true;
$x = 0;
$b = [];
while ($numNotFound) {
if ($x*$x + 1 == 10) {
array_push($b, $x, $x*-1);
$numNotFound = false;
}
$x++;
}
echo json_encode($b); #[3, -3]
Updated
This solution does not use the fact that -1 * -1 = 1. It will output the first number found as the first element in the array. If x=-3 then [-3,3] or if x=3 [3,-3].
$numNotFound = TRUE;
$x = 0;
$b = [];
Do{
if ((pow($x, 2) + 1) === 10) {
array_push($b, $x, 0 - $x);
$numNotFound = FALSE;
}
$x++;
}while($numNotFound);
echo json_encode($b); //[3, -3]

How to tell if a comma delimited list of numbers obeys the natural order of numbers

I have a comma delimited list of numbers which i am converting into an array and what i want to know about the list of numbers is if the numbers listed obey a natural ordering of numbers,you know,have a difference of exactly 1 between the next and the previous.
If its true the list obeys the natural ordering,i want to pick the first number of the list and if not the list obeys not the natural order,i pick the second.
This is my code.
<?php
error_reporting(0);
/**
Analyze numbers
Condition 1
if from number to the next has a difference of 1,then pick the first number in the list
Condition 2
if from one number the next,a difference of greater than 1 was found,then pick next from first
Condition 3
if list contains only one number,pick the number
*/
$number_picked = null;
$a = '5,7,8,9,10';
$b = '2,3,4,5,6,7,8,9,10';
$c = '10';
$data = explode(',', $b);
$count = count($data);
foreach($data as $index => $number)
{
/**
If array has exactly one value
*/
if($count == 1){
echo 'number is:'.$number;
exit();
}
$previous = $data[($count+$index-1) % $count];
$current = $number;
$next = $data[($index+1) % $count];
$diff = ($next - $previous);
if($diff == 1){
$number_picked = array_values($data)[0];
echo $number_picked.'correct';
}
elseif($diff > 1){
$number_picked = array_values($data)[1];
echo $number_picked.'wrong';
}
}
?>
The problem i am having is to figure out how to test the difference for all array elements.
No loops are needed, a little bit of maths will help you here. Once you have your numbers in an array:
$a = explode(',', '5,7,8,9,10');
pass them to this function:-
function isSequential(array $sequence, $diff = 1)
{
return $sequence[count($sequence) - 1] === $sequence[0] + ($diff * (count($sequence) - 1));
}
The function will return true if the numbers in the array follow a natural sequence. You should even be able to adjust it for different spacings between numbers, eg 2, 4, 6, 8, etc using the $diff parameter, although I haven't tested that thoroughly.
See it working.
Keep in mind that this will only work if your list of numbers is ordered from smallest to largest.
Try using a function to solve this... Like so:
<?php
error_reporting(0);
/**
Analyze numbers
Condition 1
if from number to the next has a difference of 1,then pick the first number in the list
Condition 2
if from one number the next,a difference of greater than 1 was found,then pick next from first
Condition 3
if list contains only one number,pick the number
*/
$number_picked = null;
$a = '5,7,8,9,10';
$b = '2,3,4,5,6,7,8,9,10';
$c = '10';
function test($string) {
$data = explode(',', $string);
if(count($data) === 1){
return 'number is:'.$number;
}
foreach($data as $index => $number)
{
$previous = $data[($count+$index-1) % $count];
$current = $number;
$next = $data[($index+1) % $count];
$diff = ($next - $previous);
if($diff == 1){
$number_picked = array_values($data)[0];
return $number_picked.'correct';
}
elseif($diff > 1){
$number_picked = array_values($data)[1];
return $number_picked.'wrong';
}
}
}
echo test($a);
echo test($b);
echo test($c);
?>
You already know how to explode the list, so I'll skip that.
You already handle a single item, so I'll skip that as well.
What is left, is checking the rest of the array. Basically; there's two possible outcome values: either the first element or the second. So we'll save those two first:
$outcome1 = $list[0];
$outcome2 = $list[1];
Next, we'll loop over the items. We'll remember the last found item, and make sure that the difference between the new and the old is 1. If it is, we continue. If it isn't, we abort and immediately return $outcome2.
If we reach the end of the list without aborting, it's naturally ordered, so we return $outcome1.
$lastNumber = null;
foreach( $items as $number ) {
if($lastNumber === null || $number - $lastNumber == 1 ) {
// continue scanning
$lastNumber = $number;
}
else {
// not ordened
return $outcome2;
}
}
return $outcome1; // scanned everything; was ordened.
(Note: code not tested)
To avoid the headache of accessing the previous or next element, and deciding whether it still is inside the array or not, use the fact that on a natural ordering the item i and the first item have a difference of i.
Also the corner case you call condition 3 is easier to handle outside the loop than inside of it. But easier still, the way we characterize a natural ordered list holds for a 1-item list :
$natural = true;
for($i=1; $i<$count && $natural; $i++)
$natural &= ($data[$i] == $data[0] + $i)
$number = $natural ? $data[0] : $data[1];
For $count == 1 the loop is never entered and thus $natural stays true : you select the first element.

if multiple random numbers are all equal return true

Im working on some random generator, and it's something like roll a dices, if all dices are returning same numbers than you won a game if not than you try again.
To get six dices i used mt_rand function and for every dice separately, so i have this:
$first = mt_rand(1,6);
$second = mt_rand(1,6);
$third = mt_rand(1,6);
$fourth = mt_rand(1,6);
$fifth = mt_rand(1,6);
$sixth = mt_rand(1,6);
But i don't know how to return if operand for multiple random generated numbers.
If i would use like 2 dices i would just use
if ( $first === $second )
that would return true if first and second dices, both have returned number 2
But how do i use it if i want to echo true if all 6 dices to return number 2 ?
Edit:
number 2 is just an example if i would need only number 2 i know how to do it with array and variable but point is that i need only all numbers to match, it doesn't matter which ones from 1 to 6. And first answer actually works but let's see if it's possible to do with array.
Use arrays to make your life easier (e.g. $dices with indices from 0 to 5)
Just put it in a loop and check at every iteration. If one dice isn't 2, $allDicesSameNumber wil be false.
$number = mt_rand(1, 6);
$allDicesSameNumber = true;
for ($i = 1; $i < 6 /* dices */; $i++) {
$dices[$i] = mt_rand(1, 6);
if ($dices[$i] !== $number)
$allDicesSameNumber = false;
}
$diceCount = 6;
$diceArray = array();
for($i=1; $i<=$diceCount; $i++) {
$diceArray[] = mt_rand(1,6);
}
if (count(array_count_values($diceArray) == 1) {
echo 'All the dice have the same number';
}

Categories