Keras
neural networks
modulus
machine learning
AI programming

Keras Making a neural network to find a number's modulus

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

A neural network can learn to approximate a modulus operation over a bounded input range, but that does not mean it is the right tool for computing modulus in production. For a deterministic arithmetic rule such as n % d, direct code is exact, faster, and simpler. The neural-network version is mainly useful as a learning exercise in function approximation and representation choice.

Start by choosing the right problem framing

The modulus operation behaves differently depending on what stays fixed.

If the divisor is fixed, such as "predict n % 7," the problem is easiest to frame as classification because the output can only be one of a small set of discrete classes:

  • '0'
  • '1'
  • '2'
  • '3'
  • '4'
  • '5'
  • '6'

That is usually better than trying to make the network regress directly to a number and hoping it lands exactly on integers.

A simple Keras classification model

Here is a small example that learns n % 7 for integers in a bounded range:

python
1import numpy as np
2import tensorflow as tf
3
4divisor = 7
5x = np.arange(0, 5000, dtype=np.float32).reshape(-1, 1)
6y = (x[:, 0] % divisor).astype(np.int32)
7
8model = tf.keras.Sequential([
9    tf.keras.layers.Input(shape=(1,)),
10    tf.keras.layers.Normalization(),
11    tf.keras.layers.Dense(32, activation="relu"),
12    tf.keras.layers.Dense(32, activation="relu"),
13    tf.keras.layers.Dense(divisor, activation="softmax"),
14])
15
16model.layers[0].adapt(x)
17
18model.compile(
19    optimizer="adam",
20    loss="sparse_categorical_crossentropy",
21    metrics=["accuracy"],
22)
23
24model.fit(x, y, epochs=10, batch_size=64, verbose=0)

To make predictions:

python
1test_values = np.array([[10.0], [11.0], [12.0], [13.0]], dtype=np.float32)
2predictions = model.predict(test_values, verbose=0)
3predicted_classes = np.argmax(predictions, axis=1)
4
5print(predicted_classes)
6print(test_values[:, 0] % divisor)

This is the most sensible Keras setup for a fixed modulus problem.

Why this is still a weak use case for neural networks

Even if the network learns well over the training range, modulus is not naturally a smooth function over real numbers in the way neural networks usually prefer. It is periodic and discrete.

That creates two practical problems:

  • exactness is hard
  • extrapolation beyond the training range can be unreliable

A network may score well on nearby values but still make obvious mistakes outside the region it saw during training. By contrast, the direct arithmetic rule:

python
value = 123456
print(value % 7)

is exact for every valid integer input and needs no training data at all.

If the divisor varies too, the problem gets harder

Suppose the input is two numbers, n and d, and the target is n % d. You can still create a training dataset:

python
1pairs = []
2targets = []
3
4for n in range(100):
5    for d in range(1, 11):
6        pairs.append([n, d])
7        targets.append(n % d)

But now the output range depends on the divisor, which makes the learning task more awkward. A fixed-size softmax classifier is no longer a natural target unless you constrain the divisor range and maximum remainder carefully.

At that point, the exercise becomes more about modeling choices than about a genuinely good use of neural networks.

What this exercise is good for

Even though modulus itself is not a practical neural-network target, the exercise can still teach useful concepts:

  • function approximation
  • feature scaling
  • classification versus regression framing
  • bounded-output modeling
  • failure modes of extrapolation

That makes it a decent educational toy problem, as long as you do not confuse "the model can approximate this" with "the model should be used for this."

Common Pitfalls

The biggest mistake is treating modulus as a regression problem and then being surprised when outputs are close to the right answer but not exactly correct integers.

Another common issue is expecting perfect generalization outside the training range. Neural networks do not discover the exact arithmetic rule just because they fit training data well.

People also skip normalization or choose too little training coverage, which makes even the toy problem harder than it needs to be.

Finally, do not use a neural network for modulus in real software when direct arithmetic is available. This is an educational exercise, not a production recommendation.

Summary

  • For a fixed divisor, modulus is best framed as a classification problem in Keras.
  • A small dense network can learn n % d over a bounded range.
  • Direct arithmetic is still exact and superior for real applications.
  • Neural networks may approximate the pattern without learning the true exact rule for all inputs.
  • Treat this as a learning exercise in modeling, not as a practical replacement for %.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.