Home > OS >  Find if a number is divisible in a range of numbers
Find if a number is divisible in a range of numbers

Time:11-11

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:

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?

CodePudding user response:

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 `rem` x == 0) [rstart..rend]
  • Related