public class Main {
// 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) % 5
public static boolean isDivisibleByFive(String bin) {
// remainder modulo 5 while scanning bits
int remainder = 0;
// scan each bit of the binary number
for (int i = 0; i < bin.length(); i++) {
// convert '0' or '1' to integer 0 or 1
int b = bin.charAt(i) - '0';
// update remainder using modulo arithmetic
remainder = (remainder * 2 + b) % 5;
}
// divisible if final remainder is zero
return remainder == 0;
}
public static void main(String[] args) {
// read an n-bit binary number as a string
String bin = "01000110"; // 70
boolean divisible = isDivisibleByFive(bin);
System.out.println("Binary number: " + bin);
System.out.println("Divisible by 5: " + (divisible ? "yes" : "no"));
/*
Example walk-through for bin = 01000110:
Start: remainder = 0
bit = 0 → remainder = (0*2 + 0) % 5 = 0
bit = 1 → remainder = (0*2 + 1) % 5 = 1
bit = 0 → remainder = (1*2 + 0) % 5 = 2
bit = 0 → remainder = (2*2 + 0) % 5 = 4
bit = 0 → remainder = (4*2 + 0) % 5 = 3
bit = 1 → remainder = (3*2 + 1) % 5 = 2
bit = 1 → remainder = (2*2 + 1) % 5 = 0
bit = 0 → remainder = (0*2 + 0) % 5 = 0
Final remainder = 0 → divisible by 5
*/
}
}
/*
run:
Binary number: 01000110
Divisible by 5: yes
*/