How to determine whether an n‑bit binary number is divisible by 5 in Pascal

1 Answer

0 votes
program DivisibleByFive;

{$mode objfpc}

{
  function to compute whether a binary number is divisible by 5
  it processes the bits left to right and keeps track of the remainder modulo 5
  for each bit b:
      remainder := (remainder * 2 + b) mod 5
}
function IsDivisibleByFive(const bin: string): boolean;
var
  remainder: integer;
  i: integer;
  b: integer;
begin
  remainder := 0;

  { scan each bit of the binary number }
  for i := 1 to Length(bin) do
  begin
    { convert '0' or '1' to integer 0 or 1 }
    b := Ord(bin[i]) - Ord('0');

    { update remainder using modulo arithmetic }
    remainder := (remainder * 2 + b) mod 5;
  end;

  { divisible if final remainder is zero }
  Result := (remainder = 0);
end;

var
  bin: string;
  divisible: boolean;

begin
  { read an n-bit binary number as a string }
  bin := '01000110';  { 70 }

  divisible := IsDivisibleByFive(bin);

  WriteLn('Binary number: ', bin);
  
  if divisible then
    WriteLn('Divisible by 5: yes')
  else
    WriteLn('Divisible by 5: no');

  {
    Example walk-through for bin = 01000110:

    Start: remainder = 0

    bit = 0 → remainder = (0*2 + 0) mod 5 = 0
    bit = 1 → remainder = (0*2 + 1) mod 5 = 1
    bit = 0 → remainder = (1*2 + 0) mod 5 = 2
    bit = 0 → remainder = (2*2 + 0) mod 5 = 4
    bit = 0 → remainder = (4*2 + 0) mod 5 = 3
    bit = 1 → remainder = (3*2 + 1) mod 5 = 2
    bit = 1 → remainder = (2*2 + 1) mod 5 = 0
    bit = 0 → remainder = (0*2 + 0) mod 5 = 0

    Final remainder = 0 → divisible by 5
  }
end.


{
run:

Binary number: 01000110
Divisible by 5: yes

}

 



answered Jun 27 by avibootz
edited Jun 28 by avibootz

Related questions

...