Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checking if a number is divisible by 6 PHP

Tags:

php

modulus

I want to check if a number is divisible by 6 and if not I need to increase it until it becomes divisible.

how can I do that ?

like image 949
Utku Dalmaz Avatar asked Jan 19 '10 01:01

Utku Dalmaz


People also ask

How do you check if a number is divisible by 6?

Divisibility by 6 is determined by checking the original number to see if it is both an even number (divisible by 2) and divisible by 3. This is the best test to use. If the number is divisible by six, take the original number (246) and divide it by two (246 ÷ 2 = 123).

How do you check if a number is divisible by any number?

A number is divisible by another number if it can be divided equally by that number; that is, if it yields a whole number when divided by that number. For example, 6 is divisible by 3 (we say "3 divides 6") because 6/3 = 2, and 2 is a whole number.


2 Answers

if ($number % 6 != 0) {   $number += 6 - ($number % 6); } 

The modulus operator gives the remainder of the division, so $number % 6 is the amount left over when dividing by 6. This will be faster than doing a loop and continually rechecking.

If decreasing is acceptable then this is even faster:

$number -= $number % 6; 
like image 97
ZoFreX Avatar answered Oct 10 '22 20:10

ZoFreX


if ($variable % 6 == 0) {     echo 'This number is divisible by 6.'; }: 

Make divisible by 6:

$variable += (6 - ($variable % 6)) % 6; // faster than while for large divisors 
like image 43
Bandi-T Avatar answered Oct 10 '22 21:10

Bandi-T