I need to divide an integer value into x parts (dynamic) using php inside a for loop (Note:Both the number to be split and the split value are dynamic)
for eg: I have a value 127 and divide it into 2parts it would be 63 and 64.
$number = y; //for example is 127
$parts = x; //for example is 2
for($i=1;$i<$parts;$i++){
//first iteration should output 63
//second iteration should output 64 (the last iteration should be always higher is the $number is not divisible by $parts)
}
Check out this example. I use the modulo operator. This works whether it's an even or odd number. You could wrap this all in a function also.
$x = 127;
$a = 0;
$b = 0;
$a = floor($x/2);
$b = ($x % 2) + $a;
echo "A: " . $a . "| B: " . $b; //A: 63| B: 64
Try it in a function.
function remainders($x, $num) {
$results = array();
$firstOp = floor($x / $num);
for($a = 1; $a <= $num; $a++) {
if($a != $num) {
$results[] = $firstOp;
}
else {
if($x % 2 == 1) {
$results[] = $firstOp + 1;
}
else {
$results[] = $firstOp;
}
}
}
return $results;
}
Then you can iterate through the returned array or do what you want.
$splitNum = remainders(183, 4); //split the number 183 in 4 parts.
foreach($splitNum as $var) { echo $var . ", "; }
Try this:
$number = 127; //for example is 127
$parts = 3; //for example is 3
$sep = ", ";
$n=floor($number/$parts);
for($i=1;$i<=$parts;$i++){
if ($i==$parts) {
$n=$number-($n*($i-1));
$sep="";
}
echo $n.$sep;
}
Related
I use the following to find out the common divisors.
But in some case the count of divisors are not satisfied.
My Code :
$x = 66928;
$y = 66992;
$c_a = [];
$c_b = [];
$d = 1;
while ($d_a <= $x) {
if (is_int($x / $d)) $c_a[] = $d;
$d++;
}
$d = 1;
while ($d_b <= $y) {
if (is_int($y / $d)) $c_b[] = $d;
$d++;
}
echo count($c_a);
echo count($c_b);
// Output
$c_a = 20;
$c_b = 20;
Because, in some cases, it won't work.
Is this type of calculation is right ?
or any suggestions ?
As per asked in comment, to count the common factors of the two no. will be as like this.
<?php
$a = 66928;
$b = 66992;
$min = ($a < $b ) ? $a : $b;
$commomn_factors_count = 0;
for ($i = 1; $i < $min/2; $i++) {
if (($a%$i==0) && ($b%$i==0)) {
$commomn_factors_count++;
}
}
var_dump($commomn_factors_count);
You can you this code to get the fastest result to find the number of common divisors between two numbers:
// Function to calculate gcd of two numbers
function gcd($a, $b)
{
if ($a == 0)
return $b;
return gcd($b % $a, $a);
}
/* Function to calculate all common
* divisors of two given numbers
* a, b --> input integer numbers
*/
function commDiv($a, $b)
{
// find gcd of a, b
$n = gcd($a, $b);
// Count divisors of n.
$result = 0;
for ($i = 1; $i <= sqrt($n);
$i++)
{
// if 'i' is factor of n
if ($n % $i == 0)
{
// check if divisors
// are equal
if ($n / $i == $i)
$result += 1;
else
$result += 2;
}
}
return $result;
}
// Driver Code
$a = 10; $b = 15;
echo(commDiv($a, $b));
How can I write a function that gives me number of the character that is passed to it
For example, if the funciton name is GetCharacterNumber and I pass B to it then it should give me 2
GetCharacterNumber("A") // should print 1
GetCharacterNumber("C") // should print 3
GetCharacterNumber("Z") // should print 26
GetCharacterNumber("AA") // should print 27
GetCharacterNumber("AA") // should print 27
GetCharacterNumber("AC") // should print 29
Is it even possible to achieve this ?
There is a function called ord which gives you the ASCII number of the character.
ord($chr) - ord('A') + 1
gives you the correct result for one character. For longer strings, you can use a loop.
<?php
function GetCharacterNumber($str) {
$num = 0;
for ($i = 0; $i < strlen($str); $i++) {
$num = 26 * $num + ord($str[$i]) - 64;
}
return $num;
}
GetCharacterNumber("A"); //1
GetCharacterNumber("C"); //3
GetCharacterNumber("Z"); //26
GetCharacterNumber("AA"); //27
GetCharacterNumber("AC"); //29
GetCharacterNumber("BA"); //53
?>
Not very efficient but gets the job done:
function get_character_number($end)
{
$count = 1;
$char = 'A';
$end = strtoupper($end);
while ($char !== $end) {
$count++;
$char++;
}
return $count;
}
echo get_character_number('AA'); // 27
demo
This works because when you got something like $char = 'A' and do $char++, it will change to 'B', then 'C', 'D', … 'Z', 'AA', 'AB' and so on.
Note that this will become the slower the longer $end is. I would not recommend this for anything beyond 'ZZZZ' (475254 iterations) or if you need many lookups like that.
An better performing alternative would be
function get_character_number($string) {
$number = 0;
$string = strtoupper($string);
$dictionary = array_combine(range('A', 'Z'), range(1, 26));
for ($pos = 0; isset($string[$pos]); $pos++) {
$number += $dictionary[$string[$pos]] + $pos * 26 - $pos;
}
return $number;
}
echo get_character_number(''), PHP_EOL; // 0
echo get_character_number('Z'), PHP_EOL; // 26
echo get_character_number('AA'), PHP_EOL; // 27
demo
Use range and strpos:
$letter = 'z';
$alphabet = range('a', 'z');
$position = strpos($alphabet, $letter);
For double letters (eg zz) you'd probably need to create your own alphabet using a custom function:
$alphabet = range('a', 'z');
$dictionary = range('a','z');
foreach($alphabet AS $a1){
foreach($alphabet AS $a2) {
$dictionary[] = $a1 . $a2;
}
}
Then use $dictionary in place of $alphabet.
Here is the full code that does what you want.
Tested it and works perfectly for the examples you gave.
define('BASE', 26);
function singleOrd($chr) {
if (strlen($chr) == 1) {
return (ord($chr)-64);
} else{
return 0;
}
}
function multiOrd($string) {
if (strlen($string) == 0) {
return 0;
} elseif (strlen($string) == 1) {
return singleOrd($string);
} else{
$sum = 0;
for($i = strlen($string) - 1; $i >= 0; $i--) {
$sum += singleOrd($string[$i]) * pow(BASE, $i);
}
}
return $sum;
}
I think ord should be a more efficient way to have your number :
$string = strtolower($string);
$result = 0;
$length = strlen($string);
foreach($string as $key=>$value){
$result = ($length -$key - 1)*(ord($value)-ord(a)+1);
}
and result would contain what you want.
Simple question, how do I get every option when dividing a number? For example:
24 by 6 returns 6, 12, 18, 24
24 by 4 returns 4, 8, 12, 16, 20, 24
24 by 5 returns false
I've got a number in my database, for example 2, and my counter, for example 14. That means every time my counter hits the second number, I want to fire my event. So I thought, if I have the solutions 2, 4, 6, etc, and my counter is equal to one of the solutions, I can fire my event.
It's rather trivial to make.
<?php
/**
* #param int $number The beginning number
* #param int $divider The number dividing by
*
* #return array
* #throws Exception In case $number is not divisible by $divider
*/
function get_number_sequence($number, $divider) {
//In case $number is not divisible by $divider, throw an Exception.
if ($number % $divider !== 0) {
throw new Exception("$number is not divisible by $divider");
}
//Return an array from $divider to $number in steps of $divider.
$result = range($divider, $number, $divider);
return $result;
}
/*
* Testing begins
*/
try {
echo "<pre>";
echo implode(", ", get_number_sequence(24, 4)) . PHP_EOL;
echo implode(", ", get_number_sequence(24, 6)) . PHP_EOL;
echo implode(", ", get_number_sequence(24, 5)) . PHP_EOL;
echo "</pre>";
}
catch (Exception $e) {
echo "Invalid: " . $e->getMessage();
}
Some Points
Don't return false if something exceptional happens, use an Exception as shown in the example.
Use the modulus operator to determine if the number is divisible or not.
Return an array, not a string. It's easier to work with.
should be easy
do a modulus on X by Y . If 0 then do a division on X by Y. create a loop which will run from 1 to (division on X by Y) and output Y multiplied by the loop counter
function steps($target,$step) {
if (($target % $step) != 0)
return FALSE;
$steps = range($step,$target,$step);
return $steps;
}
$target = 24;
for ($step = 2; $step < 13; ++$step) {
echo '$step = ',$step,PHP_EOL;
$steps = steps($target,$step);
var_dump($steps);
}
function findQuotients($number, $divider)
{
$arr = array();
if($number % $divider != 0)
{
//return "false";
}
else
{
$loop = $number / $divider;
//$output="";
for($i = 1; $i <= $loop; $i++)
{
//$output .= $i * $divider. " ";
array_push($arr, $i * $divider);
}
}
return $arr;
}
echo print_r(findQuotients(24, 6));
echo print_r(findQuotients(24, 4));
echo print_r(findQuotients(24, 5));
Try this
$number = 24;
$divider = 6;
if($number % $divider != 0 )
{
return false;
}
$div = $number / $divider;
for($i = 1; $i <= $div; $i++)
{
echo $i*$divider;
}
The following snippet will do the trick. It's a simple loop to iterate until $num is <= 0. $num will be subtracted by the divider and each turn the next multiple of $div will be stored as a "divider step".
$num = 24;
$div = 4;
if ($num % $div != 0) {
exit('invalid');
}
$divider = array();
for ($i = 1; $num > 0; $i++) {
$divider[] = ($i * $div);
$num -= $div;
}
echo 'in: ' . $num . '<br />';
echo 'div: ' . $div . '<br />';
echo '<pre>';
print_r($divider);
exit;
based on your description you want to multiply a number and then on a given result you want to white a function:
$num = 6;
$counter = 2;
$solution = 24;
while ($num * $counter) {
$result= $num * $counter;
if ($result = $solution) {
echo $result;
// here would go your event
break;
}
}
i have:
# = 1
# = 0,5
% = 0
max = 10
for example if i have: 3 then should show me:
###$$$$$$$
if i have 3,5 :
####$$$$$$
etc
if i have 3,99 then = 3,5
if i have 3,49 then = 3,0
etc
how can i use this with foreach or for?
for whole number i can make:
$number = 8;
$one = 10 - $number;
$three = 0 + $number;
and
for($i=1;$i <= $one){
echo "#";
}
for($i=1;$i <= $three){
echo "$";
}
but how is the best solution if $number = 3,57
If I've understood what you're after, this should do what you want:
<?php
function printItOut($number) {
$s = '';
for ($i = 0; $i < 10; $i++) {
if ($i < $number%10) {
$s .= '#';
} else if ($i < ($number+0.5)%10) {
$s .= '#';
} else {
$s .= '$';
}
}
return $s;
}
echo printItOut(3.49), "\n";
echo printItOut(3.5), "\n";
echo printItOut(3.99), "\n";
echo printItOut(4), "\n";
Outputs:
###$$$$$$$
####$$$$$$
####$$$$$$
####$$$$$$
Inside the for loop, I using the modulus operator to find the integer remainder of dividing $number by 10. So 3%10 gives a result of 3, 3.49%10 also results in 3.
In the first 'else if' block, I'm checking whether the number is 0.5 or more, since (3.49+0.5) is 3.99, and 3.99%10 is 3; but 3.5+0.5 is 4, and 4%10 is 4.
The following code is displaying INF as the result. How can I fix it?
<?php
function fibonacci($n)
{
$a = 1;
$b = 1;
$result = 0;
for ($i = 0; $i < $n; $i=$i+1)
{
$sum = $a + $b;
$a = $b;
$b = $sum;
if ($a % 2 == 0)
{
$result = $result + $a;
}
}
echo "<br/>" . $result;
}
echo fibonacci(400000);
?>
The number is too big to display, and INF is a pretty good guess :) (fibonacci(1000) gives you a number with 210 digits).
100: 22 digits, 110: 24 digits, 120: 25 digits, 130: 27 digits
If you extrapolate that, you would end up with about (400000 / 10) * 2 = 80000 digits.
The following implements your logic using bcmath to prevent the INF error.
function fibonacci($n)
{
$a = '1'; $b = '1'; $result = '0';
for ($i = 0; $i < $n; $i++) {
$sum = bcadd($a,$b);
$a = $b;
$b = $sum;
if (bcmod($a,'2') == '0') {
$result = bcadd($result,$a);
}
}
echo "<br />".$result;
}
As your fibonacci function doesn't actually return any value, there's no point in echo fibonacci(400000)
EDIT
However, your logic is completely flawed. The following should give you the correct result for the problem you're trying to solve (again using bcmath):
function fibonacci($n)
{
$a = '0'; $b = '1'; $sum = '0';
$sum = '0';
do {
$fib = bcadd($a,$b);
$a = $b;
$b = $fib;
if (bccomp($fib,$n) == -1) {
if (bcmod($fib,'2') == '0') {
$sum = bcadd($sum,$fib);
}
}
++$i;
} while (bccomp($fib,$n) == -1);
return $sum;
}
echo fibonacci(4000000);
Rather than simply executing it to get the result, look to see how it works and what it's actually doing