L5RK
L5RK

Reputation: 109

Haskell type issue regarding conversion to a float

I have the following code to test for primeness

prime x n = if (n==1) then True else (if (mod x n == 0) then False else prime x (n-1))

However I want to create a separate function so that I have to input only 1 number, like so:

isPrime x = prime x (floor(sqrt(x)))

However, I am getting an error when I try this:

 Ambiguous type variable `a0' arising from a use of `isPrime'
  prevents the constraint `(Integral a0)' from being solved.

I also wanted to try using partial functions to apply this but I couldn't get that to work either. Any advice and help would be greatly appreciated.

Upvotes: 0

Views: 52

Answers (1)

chepner
chepner

Reputation: 532218

This is actually simpler to solve by not computing a square root in the first place. Instead, start with small values of n and work up to the square root of x (which you can detect by comparing n * n and x).

-- Treat 1 and 2 as base cases so we can increment n a little faster;
-- The interesting values of n are the odd integers 3, 5, 7, ...
prime 1 _ = False
prime 2 _ = True
prime x n | n * n > x = True
          | mod x n == 0 = False
          | otherwise = prime x (n + 2)

isPrime x = prime x 3

(It's less efficient, as computing n*n repeatedly is more expensive than computing a square root. But if you are concerned about efficiency, then you'll implement the Sieve of Erastosthenes or something similar, rather than testing every potential odd factor.)

Upvotes: 1

Related Questions