Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find if a number is divisible in a range of numbers

I do want to compare an integer (rstart) with an integer (number) in the following way (C code):

#include <stdio.h>
#include <stdlib.h>

int main (void){
    int rstart = 15, rend = 25, number = 629;
    while (rstart <= rend){
        rstart++;
        if (number % rstart == 0){
            return number % rstart;
        }
    }   
    return number % rstart;
}

Now I do know how to write something like this in c or python but I do have no clue how to do it in Haskell.

I did start out with the following:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

dividesRange :: Integer -> Integer -> Integer -> Bool
dividesRange number rstart rend = 

I do not know how I would implement the while loop from C in Haskell. I know I could use all if statements but that is inefficient in my opinion. Is there an easy way to write this in Haskell?

>Solution :

dividesRange :: Integer -> Integer -> Integer -> Bool
dividesRange number rstart rend = go rstart where
  go x
    | x > rend = False
    | otherwise = number `rem` x == 0 || go (x+1)

How it works:

  1. We use a helper function go.
  2. The base case is when x (rstart), is greater than rend. In that case we return False.
  3. Otherwise we check if the remainder of number divided by x is zero. If so, we return True and don’t recurse further.
  4. Otherwise we increase x and call go again.

Using any we can rewrite the above as follows:

dividesRange2 :: Integer -> Integer -> Integer -> Bool
dividesRange2 number rstart rend = any (\x -> number `div` x == 0) [rstart..rend]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading