Saturday, January 21, 2012

Modulus 11

Problem: create a program which will ask for an input number and determine whether it is a multiple of 11. Range: 1-100 digits (not one to one hundred, but 100 digits)

CLUE: use string for the input for even the long long int cannot hold a 100-digit number

Input:
132
1452
5431
23191344
537838436526336
1451999999998548
123454865432545321
33673831487966326168512

Output:
YES
YES
NO
YES
YES
YES
NO
YES

Solution:
<?php
  $input = "81402749386839761113321";
  $divider = 11; //mod
  $remainder = '';

  echo $input;
  echo "<br>";

  if(strlen($input) >= 0 && strlen($input) <= 100)
  {
    $input = str_split($input, 2);

    for($i=0, $n=count($input); $i<$n; $i++)
    {
      $divisor = intval($remainder . $input[$i]);
      $remainder = intval($divisor % $divider);
    }

    if($remainder == 0)
      echo "YES";
    else
      echo "NO";
  }
?>

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...