What does the percent sign mean in PHP? - php

What exactly does this mean?
$number = ( 3 - 2 + 7 ) % 7;

It's the modulus operator, as mentioned, which returns the remainder of a division operation.
Examples: 3%5 returns 3, as 3 divided by 5 is 0 with a remainder of 3.
5 % 10 returns 5, for the same reason, 10 goes into 5 zero times with a remainder of 5.
10 % 5 returns 0, as 10 divided by 5 goes exactly 2 times with no remainder.
In the example you posted, (3 - 2 + 7) works out to 8, giving you 8 % 7, so $number will be 1, which is the remainder of 8/7.

It is the modulus operator:
$a % $b = Remainder of $a
divided by $b.
It is often used to get "one element every N elements". For instance, to only get one element each three elements:
for ($i=0 ; $i<10 ; $i++) {
if ($i % 3 === 0) {
echo $i . '<br />';
}
}
Which gets this output:
0
3
6
9
(Yeah, OK, $i+=3 would have done the trick; but this was just a demo.)

It is the modulus operator. In the statement $a % $b the result is the remainder when $a is divided by $b

Using this operator one can easily calculate odd or even days in month for example, if needed for schedule or something:
<?php echo (date(j) % 2 == 0) ? 'Today is even date' : 'Today is odd date'; ?>

% means modulus.
Modulus is the fancy name for "remainder after divide" in mathematics.
(numerator) mod (denominator) = (remainder)
In PHP
<?php
$n = 13;
$d = 7
$r = "$n % $d";
echo "$r is ($n mod $d).";
?>
In this case, this script will echo
6 is (13 mod 7).
Where $r is for the remainder (answer), $n for the numerator and $d for the denominator. The modulus operator is commonly used in public-key cryptography due to its special characteristic as a one-way function.

Since so many people say "modulus finds the remainder of the divisor", let's start by defining exactly what a remainder is.
In mathematics, the remainder is the amount "left over" after
performing some computation. In arithmetic, the remainder is the
integer "left over" after dividing one integer by another to produce
an integer quotient (integer division).
See: http://en.wikipedia.org/wiki/Remainder
So % (integer modulus) is a simple way of asking, "How much of the divisor is left over after dividing?"
To use the OP's computation of (3 - 2 + 7) = 8 % 7 = 1:
It can be broken down into:
(3 - 2 + 7) = 8
8 / 7 = 1.143 #Rounded up
.143 * 7 = 1.001 #Which results in an integer of 1
7 can go into 8 1 time with .14 of 7 leftover
That's all there is to it. I hope this helps to simplify how exactly modulus works.
Additional examples using different divisors with 21.
Breakdown of 21 % 3 = 0:
21 / 3 = 7.0
3 * 0 = 0
(3 can go into 21 7 times with 0 of 3 leftover)
Breakdown of 21 % 6 = 3:
21 / 6 = 3.5
.5 * 6 = 3
(6 can go into 21 3 times with .5 of 6 leftover)
Breakdown of 21 % 8 = 5:
21 / 8 = 2.625
.625 * 8 = 5
(8 can go into 21 2 times with .625 of 8 leftover)

Related

Find a number by given digit

Let’s say I have a series of numbers like:
12345678910111213141516... (until unlimited)
Then I would like to get a number from it by given digit. For example:
Digit 10th: 1
Digit 17th: 3
...
I have tried to make the algorithm to do it by using PHP but it always showed me an error due to the looping that I made was out of memory size if the given digit that I gave is more than 10.000.000. Allowed Memory Size of 134217728 Bytes Exhausted
How do I deal with this without having to modify memory_limit on php.ini file?
Here are what I have tried to figure the algorithm out: I benchmark the maximum of upper limit of the loop that my local machine could handle, and I found out it's 10.000.000, then I assumed I need to make a separate loop if the given digit/parameter is more than 10.000.000. But in the end I still got that error of out of memory size. Really grateful in advance.
<?php
/*
* benchmark result:
* max digit = 10.000.000
*/
$benchmarkedDigit = 10000000;
$digit = 1000000000000; // it could be dynamically assigned, i.e. a parameter. In this case will show an error since the given digit is 10 trillion
$s = '';
if ($digit > $benchmarkedDigit) {
$mod = fmod($digit, $benchmarkedDigit);
$div = $digit / $benchmarkedDigit;
for ($x = 1; $x <= $div; $x++) {
$upperLimit = ($x * $benchmarkedDigit);
for ($y = ($upperLimit - $benchmarkedDigit + 1); $y <= $upperLimit; $y++) {
$s .= $y;
}
// so it could be:
// 1 - 10.000.000
// 10.000.001 - 20.000.000
// 20.000.001 - 30.000.000
// ...
}
// loop for the rest of the fmod(), if its result is not 0
for ($i = ($upperLimit + 1); $i <= ($upperLimit + $mod); $i++) {
$s .= $i;
}
} else {
for ($x = 1; $x <= $digit; $x++) {
$s .= $x;
}
}
echo substr($s, ($digit - 1), 1);
You can use the fact that there's always 10^n - 10^(n-1) number of n-digit long numbers (even 1 digit, because I see 0 is not there).
With this knowledge, you can skip potentially huge number of numbers.
You start with n=1, and check if the number of n digit numbers is lower than the desired digit. If it is, then reduce the number of n digit numbers from the desired number, increase n by one and start again.
For example: you want to know the 512th digit in that number
Is the number of 1 digit numbers (10) lower than the desired digit (512)?
Yes, so the desired digit should be reduced by that many (512 - 9).
Is the number of 2 digit numbers (90) lower than the desired digit (503 now)?
Yes, so the desired digit should be reduced by that many (503 - 90).
Is the number of 3 digit numbers (900) lower than the desired digit(413 now)?
No, so the desired digit is one of the digits of a 3 digit number.
413 / 3 is 137 (rounded down), so it's one of the digits of the 137th 3 digit numbers (so 237).
413 % 3 (modulo) is 2, so it's the 2nd digit, so it's supposed to be 3.
There can be miscalculations in this, but the overall logic should not be far.
Edit: you could also use a generator, but this can increase the runtime for big numbers
function getNthDigit() {
for ($i = 0;; ++$i) { // Start with 0, which is the 0-th digit
foreach (str_split((string)$i) as $digit) {
yield $digit;
}
}
}
$desiredDigit = 512;
foreach (getNthDigit() as $number => $digit) {
if ($number == $desiredDigit) {
break;
}
}
// $digit should be the desired digit
<?php
function getDigit($Nth){
if($Nth < 10) return $Nth;
$no_of_digits = 1;
$current_contribution = 9;
$actual_length = 9;
$prev_length = 0;
$starting_number = 1;
$power_of_10 = 1;
while($actual_length < $Nth){
$no_of_digits++;
$current_contribution *= 10;
$prev_length = $actual_length;
$actual_length += ($current_contribution * $no_of_digits);
$power_of_10 *= 10;
$starting_number *= 10;
}
$Nth = $Nth - $prev_length;
$offset = $Nth % $no_of_digits === 0 ? intval($Nth / $no_of_digits) - 1 : intval($Nth / $no_of_digits);
$number = strval($starting_number + $offset);
for($i=1;$i<=$no_of_digits;++$i){
if(($Nth - $i) % $no_of_digits === 0){
return $number[$i-1];
}
}
}
// first 100 Digits
for($i=1;$i<=100;++$i){
echo getDigit($i),PHP_EOL;
}
Demo: https://3v4l.org/3l0I7
Algorithm:
To find the nth digit, we will first find the number and then which digit of that number to choose as an answer.
Find the number:
If we carefully observe, the series increases in a sequential manner, such as shown in the table.
Table:
| Digits| Total numbers(of current digit)| Total Digits | Total digits of whole string |
|-------|--------------------------------|--------------|-------------------------------|
| 1 | 9 | 9 | 9 |
| 2 | 90 | 180 | 189 |
| 3 | 900 | 2700 | 2889 |
| 4 | 9000 | 36000 | 38889 |
The above table shows us that if we want to find, let's say 500th digit, then it's some digit of 3 digit number. If we go for 17th digit, then it's some digit of a 2 digit number and so on.
Now, let's take 200th digit as an example. Since it's less than 2889 and greater than 189, it's from a 3 digit number.
What we would do is breakdown the 200 into a smaller number such as 200 - 189 = 11. This 11 means that it's 11th digit of some 3 digit number which started with initial 3 digit number of 100(the starting number for 3 digit).
Now, we do 11 / 3(where 3 is number of digits) and get the quotient as 3. This 3 means that it's 3 numbers past the starting number 100, which we can say as 100 + 3 = 103(since it's 100,101,102 and then the 4th one as 103).
Now, we came to know that the number is 103. All is left to find out is which digit from 103.
Note that sometimes we come across a corner case of even divisibility such as 12 / 3. In this case, we subtract 1 from the quotient since our series of 3 digits starts from 100 and not 101( and so on and so forth for other digits).
Find out the digit:
Now, we know that the number is 103 for a 200 th digit( a.k.a 11 as we calculated above). To find out which one, we write down numbers of 3 digits in sequence and closely observe them.
Sequence:
1 0 0 1 0 1 1 0 2 1 0 3 1 0 4 1 0 5 1 0 6
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
If you observe, you can understand that the most MSB digit follows a sequence of 1,4,7,10,13 etc. Second most MSB follows a sequence of 2,5,8,11,14 etc and the last MSB(which is LSB) follows a sequence of 3,6,9,12,15 etc.
So, from th above sequence, it's pretty evident that 11(which we got after breaking down 200 initially) belongs to a sequence of the 2nd most MSB digit.
So, the final answer from 103 is 0 (the 2nd digit from left).
$num = '12345678910111213141516';
echo $num[16];
Result: 3

Understanding something more about the % Modulus operator

I am learning to work with some math like PHP query and just got to the modulo, I am not quite sure in what situations to use this because of something i stumbled on and yes I did already read one of the posts here about the modulo :
Understanding The Modulus Operator %
(This explanation is only for positive numbers since it depends on the language otherwise)
The quote above is in the top answer there. But if I focus on PHP only and i use the modulo like this:
$x = 8;
$y = 10;
$z = $x % $y;
echo $z; // this outputs 8 and I semi know why.
Calculation: (8/10) 0 //times does 10 fit in 8.
0 * 10 = 0 //So this is the number that has to be taken off of the 8
8 - 0 = 8 //<-- answer
Calculation 2: (3.2/2.4) 1 //times does this fit
1 * 2.4 = 2.4 //So this is the number that has to be taken off of the 3.2
3.2 - 2.4 = 0.8 // but returns 1?
So my question is why does this exactly happen. my guess would be that in the first phase it would get 8/10 = 0,8 but this doesn't happen. So can someone explain a bit about why this happens. I understand the modulo's basics like if I do 10 % 8 = 2 and I semi understand why it doesn't return something like this: 8 % 10 = -2.
Also, is there a way to modify how the modulo works? so it would return a - value or a decimal value in the calculation? or would I need to use something else for this
Little shortened: why does this happen when I get a negative number in return and is there some other way or operator that can actually do the same and get in the negative numbers.
Modulus (%) only works for integers, so your calculation at the bottom of your example is correct...
8/10 = 0 ( integer only ), remainder = 8-(0*10) = 8.
If you instead had -ve 12 - -12%10...
-12/10 = -1 (again integer only), remainder = -12 - (10*-1) = -2
For floats - you can use fmod(http://php.net/manual/en/function.fmod.php)
<?php
$x = 5.7;
$y = 1.3;
$r = fmod($x, $y);
// $r equals 0.5, because 4 * 1.3 + 0.5 = 5.7
(Example from manual)

Modulus % give 2 in place of 0

In php:
the Modulus % gives Remainder of $x divided by $y.
I have tryed this code:
<?php
print(100000000165 % 5);
result is 2
since it should be 0
This happens because you're working on a 32bit system.
The largest integer number in 32bit php is 2147483647. That means after that (beginning with 2147483648) it's an overflow and wraps.
Your number is greater than that and so the result is: (100000000165 % 2147483648) % 5 => 1215752357 % 5 => 2
Addition: You can build the modulus function by yourself and deal with floats
$largeNumberThatBreaksInteger = 10000000000000000000165;
$modulus = $largeNumberThatBreaksInteger / PHP_INT_MAX - (int)($largeNumberThatBreaksInteger / PHP_INT_MAX) * PHP_INT_MAX;
// results in something like -9.9981352879506E+21. So you can compare it with an epsilon and know if it's 0 or not.
Dealing with floats and epsilon

Why this php code output one

I have this php code with me and i am not able to figure it out could anyone help on this.
$x = 3 - 5 % 3;
echo $x;
gives 1 in out put.
Thanks
5 % 3 = 2.
3 - 2 = 1.
There's a specific operator precedence, that causes modulo to be evaluated before minus.
It' s simple math!
% / * operators are first calculated and then
+ -
5 % 3 = 2
3 - 2 = 1
If you want to "prevent" this simply add some brackets:
$x = (3 - 5) % 3;
Of course the answer is correct. PHP parses the code like this 3 - (5 % 3)
5 % 3 is 2 and 3 - 2 gives you 1
5 % 3 is the remainder of 5 /3
It's the order of operations. Without parenthesis around the subtraction, the modulo is being evaluated first. Try this:
$x = (3 - 5) % 3;
echo $x;
% has higher presedence then -. Check out operator precedence
BODMAS - Brackets Order[^] Division Multiplication Addition Substracion .
For,
3 - 5 % 3
first,
5 % 3 gives remainder as 1
second,
3 - 1,
this gives 2.

How to determine if a digit divided by 8 is an integer?

How do I determine if a digit divided by 8 is an integer?
for example:
32 % 8 = 4, it is an integer.
25 % 8 = 3.125, it is not an integer.
I need a working code like:
if ($str % 8 == integer){
// continue working
}
the % operator, modulo, will ALWAYS return an integer - it's the remainder of the division.
If you mean you want to check if a number is evenly divisible by 8, then do
if ($str % 8 == 0) {
... evenly divisible by 8 ...
}
you can go with if (val % 8 == 0) or with more tricky ways, like val & 0x0FFF == 0 by using bitwise operators.
Somehow they work in the same way: first snippet checks if the remainder of the division by 8 is zero while second checks if number doesn't have any binary digit for 1, 2, or 4, which would make the number not divisible by 8.
I think this is what you need:
if(is_int($integer)) {
// do something with integer
}

Categories