Modular Inverse in Haskell - haskell

So far I've solved euclid, lCM,extGCD, and coprime. How would I solve for the modular Inverse(minv)? I think that "assumes a n are coprime" is confusing me.
euclid :: Integer -> Integer -> Integer
euclid 0 0 = error "GCD(0,0) is undefined"
euclid a 0 = a
euclid a b = euclid b (a `emod` b)
-- Returns the least common multiple of a and b, using the definition of lcm
-- given in class (in terms of the gcd). DO NOT use the built-in `lcm` function.
lCM :: Integer -> Integer -> Integer
lCM 0 0 = error "LCM(0,0) is undefined"
lCM a b = a*b `ediv` (euclid a b)
-- extGCD a b
-- Returns the GCD of a and b, along with x and y such that
-- GCD(a,b) = ax + by
-- calculated via the recursive extended Euclidean algorithm presented in
-- class.
extGCD :: Integer -> Integer -> (Integer,Integer,Integer)
extGCD 0 0 = error "extGCD(0,0) is undefined"
extGCD a 0 = (1,0,a) -- Base case
extGCD a b = let (q,r) = a `eDivMod` b -- q and r of a/b
(c,x,y) = extGCD b r -- Recursive call
in (x,c-q*x, y) -- Recursive results
-- coprime a b
-- Returns True if a and b are coprime (have no common factors)
coprime :: Integer -> Integer -> Bool
coprime 0 0 = error "coprime(0,0) is undefined"
coprime a b = (euclid a b) == 1
-- minv a n
-- Returns the modular inverse of a mod n. Assumes that a and n are coprime.
minv :: Integer -> Integer -> Integer
minv a n =

You can do it with your extGCD function.
If a and m are co-prime, then use your extGCD function to solve:
a*x + m*y = gcd a m = 1
That means a * x = 1 mod m, i.e. a and x are multiplicative inverses mod m.

First of all a and n must be coprime because otherwise the inverse doesn't exist. This comes from the fact that finding the inverse of a modulo n is the same as solving the congruence: ax = 1 mod n.
A linear congruence ax = b mod n has a solution only if gcd(a, n) | b. But in this case gcd(a, n) | 1 implies that gcd(a, n) = 1.
So now, to find the inverse you use Bezout identity, i.e. there exist x and y such that: gcd(a, n) = a*x + n*y. You have already found such values in your extGCD function so you can implement minv as:
minv a n = a*x + n*y
(x, y, _) = extGCD a n
It may be better to write a function with type Integer -> Integer -> Maybe Integer and return Nothing if the extGCD is different from 1:
minv a n =
| g == 1 = Just $ a*x + n*y
| otherwise = Nothing
where
(x, y, g) = extGCD a n
As an aside: the subgroup of invertible elements in Zn is precisely the set of as < n coprime with n. When n is prime this subgroup coincides with Zn without 0 and in this case Zn is a field.

Related

Fermat Primality Test Haskell

I have implemented the following two functions for establishing if n is a fermat prime number (will return n if its true, -1 if not), but it returns always -1, can't figure out why (gc is a funct taht calculates gcd)
fermatPT :: Int -> Int
fermatPT n = fermatPT' n list
where
list = [a | a <- [1..n-1]]
-- | heper function
fermatPT' :: Int -> [Int] -> Int
fermatPT' n l | gc (n, head l) == 1 && fermatTest n (head l) = fermatPT' n (tail l)
| null l = n
| otherwise = -1
where
fermatTest n a = mod (a^(n-1)) n == 1
Your function should return a boolean indicating if the given number is a prime. If you do that, you can use the all function to define this simply as
fermatPT :: Integer -> Bool
fermatPT n = all (fermatTest n) (filter (\a -> gcd n a == 1) [1..n-1])
where fermatTest n a = mod (a^(n-1)) n == 1
gcd is defined in the Prelude.
all avoids the explicit recursion that requires you to apply the test to one element of [1..n-1] at a time; its definition is effectively
all _ [] = True
all p (x:xs) = p x && all p xs
Note that mod (a ^ (n - 1)) n is inefficient, since it may require computing an absurdly large number before ultimately reducing it to the range [0..n-1]. Instead, take advantage of the fact that ab mod n == (a mod n * b mod n) mod n, and reduce the value after each multiplication. One way to implement this (not the fastest, but it's simple):
modN :: Integer -> Integer -> Integer -> Integer
modN a 0 _ = 1
modN a b n = ((a `mod` n) * (modN a (b - 1) n)) `mod` n
Then use
fermatTest n a = modN a (n-1) n == 1
Note that you could use this (with Int instead of Integer) to correctly implement fermatPT :: Int -> Bool; although the input would still be restricted to smaller integers, it won't suffer from overflow.

Haskell Memoization Codewars Number of trailing zeros of factorial n

I am trying to solve the Codewars problem called: Number of trailing zeros of N! with Haskell.
I know that I don't need to calculate the factorial to know the trailing zeros and in fact I am just counting how many many numbers are divisible by 5 and how many times for each.
I have written 2 version, one that uses memoization when defactoring a number in order to get how many times is divisible by 5 and another one that do not use memoization.
What surprise me is that the supposed DP approach takes longer than the trivial recursive one. I am probably doing something very stupid in my code.
These are the functions:
zeros x = helperZeros [1..x]
helperZeros :: [Integer] -> Integer
helperZeros = sumArrayTuple . filter (\x -> x `mod` 5 == 0)
sumArrayTuple = foldl (\acc x -> acc + (fastDef x)) 0
data Tree a = Tree (Tree a) a (Tree a)
instance Functor Tree where
fmap f (Tree l m r) = Tree (fmap f l) (f m) (fmap f r)
index :: Tree Integer -> Integer -> Integer
index (Tree _ m _) 0 = m
index (Tree l _ r) n = case (n-1) `divMod` 2 of
(q,0) -> index l q
(q,1) -> index r q
nats = go 0 1
where
go n s = Tree (go l s') n (go r s' )
where
l = n + s
r = l + s
s' = s * 2
fastDef:: Integer -> Integer
fastDef x = trace (show x) index memTreetDef x
memTreetDef = fmap (defact fastDef) nats
defact f n
| n `mod` 5 /= 0 = 0
| otherwise = 1 + f (n `div` 5)
zeros' x = helperZeros' [1..x]
helperZeros' :: [Integer] -> Integer
helperZeros' = sumArrayTuple' . filter (\x -> x `mod` 5 == 0)
sumArrayTuple' = foldl (\acc x -> acc + (def x)) 0
def n
| n `mod` 5 /= 0 = 0
| otherwise = 1 + def (n `div` 5)
What I am trying to memoize is the result of the defact function, for example if I have already calculate defact 200, then it would reuse this result to calculate defact 1000.
I am fairly new to DP in Haskell.
If you are tested your code performance with trace and show here, that is the issue: they are very slow compared to the main code. If not, performance of variants must be about the same.
The def function is a poor candidate for memoization. The average depth of recursion is not very different from 1. The rest of the complexity is reduced to the operation mod, that is, the division that is hardly more expensive than table look up (and division by constant can be optimized to multiplication).

Majority logic decoding Haskell

I have to calculate the probability of the proper decoding of a bit copied n times.
The following formula is supposed to be the answer:
In Haskell, I coded it as follows:
fac 1 = 1
fac n = fac (n-1) * n
--prob :: (Integral b, Fractional b) => (b, b) -> b
--prob :: (Int,Int) -> Double
prob (n, k)
| n==k = (0.01**k)
| otherwise = factor (n, k) * (0.01 ** k) * (0.99**(n-k)) + prob (n, (k+1))
where
factor (n, k) = (fac n / ((fac k)* (fac n-k)))
1 - prob (3,2) gives the result 0.99992575, which is incorrect, as it should be 0.99970. Does anyone know where I went wrong?
The reason is function precedence.
if you would look into the definition of prob you will see this:
(fac n-k)
because function application has the most precedence this is parsed as
((fac n) - k)
so your code should be
(fac (n-k))
which gives a result of 0.999702 on my computer.
These are a couple of best-practices the code is lacking. I infact already answered the question itself.
1- do not use tuples as input. in Haskell, functions can have multiple parameters. the syntax is f x y for calling f on x and y. the types also have similar syntax. this transforms your code to:
fac 1 = 1
fac n = fac (n-1) * n
--prob :: (Integral b, Fractional b) => b -> b -> b (two parameters of type b and output of type b)
--prob :: Int -> Int -> Double
prob n k
| n==k = (0.01**k)
| otherwise = factor n k * (0.01 ** k) * (0.99**(n-k)) + prob n (k+1)
where
factor n k = (fac n / ((fac k)* (fac (n-k))))
2- if you will notice, fac will only work on Integers, and similarly does factor. prob infact then has type of (Fractional a, Integral b) -> b -> b -> a or alternatively Integer -> Integer -> Float. why not give them their true type?
this transformation requires changing ** (which gets two floating point numbers) to ^ (which gets an Integer as it's second parameter) and using the function fromIntegral which casts an Integer to an arbitrary number Data.
fac :: Integral a => a -> a -- or alternatively Integer -> Integer
fac 1 = 1
fac n = fac (n-1) * n
prob n k
| n==k = (0.01 ^^ k)
| otherwise = fromIntegral (factor n k) * (0.01 ^^ k) * (0.99 ^^ (n-k) + prob n (k+1)
where
factor n k = div (fac n) (fac k * fac (n-k)) -- div is Integer division operator.
now prob has type of (Integral a, Floating b) => a -> a -> b which means it gets two parameters of type a (which is an Integral instance) and returns a value of type b.

Type declaration for number division

I tried all possible type declarations but I can't make this code even compile. The trick is in handling types for division. I tried Num a, Fractional a, Float a etc.
cube x = x * x * x
sum' term a next b =
if a > b
then 0
else term a + sum' term (next a) next b
integral f a b n = (h / 3) * (sum' term 0 succ n) where
h = (b - a) / n
y k = f $ a + (k * h)
term k
| k == 0 || k == n = y k
| odd k = 4 * y k
| even k = 2 * y k
main = do
print $ integral cube 0 1 100 -- 0.25
print $ (\x -> 3 * x * x) 1 3 100 -- 26
I isolated problem by deleting (/) function. This code compiles without any type declaration at all:
cube x = x * x * x
sum' term a next b =
if a > b
then 0
else term a + sum' term (next a) next b
integral f a b n = (sum' term 0 succ n) where
h = (b - a)
y k = f $ a + (k * h)
term k
| k == 0 || k == n = y k
| odd k = 4 * y k
| even k = 2 * y k
main = do
print $ integral cube 0 1 100
Another question is how to debug cases like this? Haskell's error messages doesn't help much, it's kind of hard to understand something like The type variable a0 is ambiguous or Could not deduce (a1 ~ a).
P. S. It's ex. 1.29 from SICP.
Update
Final answer is:
cube :: Num a => a -> a
cube x = x * x * x
sum' :: (Int -> Double) -> Int -> (Int -> Int) -> Int -> Double
sum' term a next b =
if a > b
then 0
else term a + sum' term (next a) next b
integral :: (Double -> Double) -> Double -> Double -> Int -> Double
integral f a b n = (h / 3) * sum' term 0 (+1) n where
h = (b - a) / n' where n' = fromIntegral n
y k = f $ a + (k * h)
term k
| k == 0 || k == n = y k'
| odd k = 4 * y k'
| even k = 2 * y k'
where k' = fromIntegral k
main = do
print $ integral cube 0 1 100 -- 0.25
print $ integral cube 0 1 1000 -- 0.25
print $ integral (\x -> 3 * x * x) 1 3 100 -- 26
/ is only used for types that are instances of Fractional, for Integral types use quot. You can use quot as an infix operator using backticks:
h = (b - a) `quot` n
The types of the two are
(/) :: Fractional a => a -> a -> a
quot :: Integral a => a -> a -> a
There are no types that are instances of both Fractional and Integral, which is why none of the type signatures would work. Unfortunately GHC doesn't know that it's impossible for a type to be an instance of both classes, so the error messages are not very intuitive. You get used to the style of GHC error messages though, and the detail they give helps a lot.
Also, as was suggested in the comments, I completely agree that all top level definitions should be given type signatures (including main). It makes error messages a lot easier to read.
Edit: Based on the comments below, it looks like what you want is something more like this (type signature-wise)
cube :: Num a => a -> a
sum' :: (Int -> Double) -> Int -> (Int -> Int) -> Int -> Double
integral :: (Double -> Double) -> Double -> Double -> Int -> Double
You will need to use fromIntegral to convert from Int to Double in h and in k. The type errors should be at least a bit more readable with these type signatures though.

Haskell Data Structure

I am trying to build a data-structure in Haskell which functions can use to avoid re-computing values. For example, say I had the function:
f :: Int -> Int -> Int
f 1 1 == 1
f m n
| abs m > n = 0
| OTHERWISE if value of f m n has already been computed by another recursive branch, return that value and add it to the "database"
| OTHERWISE return f (m-1) (n-1) + f (m - 1) n
I have already looked at memoization, but haven't been able to implement a solution :\
Suggestions? :)
A great explanation is here.
I love memoize package :)
Example (solving the "A frog is jumping up the staircase..." problem):
import Data.Function.Memoize
ladder :: Integer -> Integer -> Integer
ladder n k = g n
where g = memoize f
f 0 = 1
f x = sum [g (x - y) | y <- [1..if x < k then x else k]]

Resources