STEM

Brain Teaser: Get all numbers divisible by your choice of a number

Here’s a little brain teaser and the solution. The challenge is to get a number input from users and your task is to show all the numbers it can divide wholly (leaving no remainder) upto a certain limit. For example, if I want to know which numbers are divisible by 37, I would enter 37. And when it asks for the limit, say, I want to know all the numbers 37 can divide wholly upto 1000, I would enter 1000.

The upper limit should also be a user-input. For both inputs, there should be graceful error handling for blank, negative, fractional, and all invalid (any other non-numeric) inputs.

Hints

For graceful error handling, you’ll need to remove any leading and trailing spaces. Check if the input is blank. Check if the input is numeric or a string. If it’s numeric and it’s 1, there’s no need to waste CPU cycles because everything is divisible by 1, so this needs to be handled. If it’s numeric and zero or negative or contains a fraction, it should be handled as with any other invalid inputs and user should be notified and allowed to retry the input. For the limit input, you need to check if the limit input is also a whole number as above, but in addition you’ll need to check if the number is entered is less than the first input, in which case, it wouldn’t make sense and thus the user should be notified and allowed to retry the input.

If both inputs are valid, then proceed to actually start a loop where you check if the first input (say, n) can divide all the numbers from n to the limit input (say, m). Optionally, keep track of how many digits satisfied the criteria. For example, if I enter 10 as the first input, and 50 as the limit. The output would be:

10
20
30
40
50

which are five numbers.

Got it? Okay, good luck! (scroll down for one solution once you’re done)

If you’re stuck, the solution code along with the ability to run the solution code right from here is provided below. Click Run icon on the widget to try it out. You can click Run after each sesssion to run it again; the code is shown side-by-side.

I hope this was educational and fun. Happy coding!

For more brain teasers and puzzles, click here.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top