I want to refresh a variable value, each time I make a recursion of a function. To make it simple I will give you an example.
Lets say we give to a function a number (n) and it will return the biggest mod it can have, with numbers smaller of itself.
{- Examples:
n=5 `mod` 5
n=5 `mod` 4
n=5 `mod` 3
n=5 `mod` 2
n=5 `mod` 1
-}
example :: Integer -> Integer
example n
| n `mod` ... > !The biggest `mod` it found so far! && ... > 0
= !Then the biggest `mod` so far will change its value.
| ... = 0 !The number we divide goes 0 then end! = 0
Where ... = recursion ( I think)
I don't know how I can describe it better. If you could help me it would be great. :)
You can write it as you described:
example :: Integer -> Integer
example n = biggestRemainder (abs n) 0
where
biggestRemainder 0 biggestRemainderSoFar = biggestRemainderSoFar
biggestRemainder divisor biggestRemainderSoFar = biggestRemainder (divisor - 1) newBiggestRemainder
where
thisRemainder = n `mod` divisor
newBiggestRemainder = case thisRemainder > biggestRemainderSoFar of
True -> thisRemainder
False -> biggestRemainderSoFar
This function can also be written more easily as
example2 :: Integer -> Integer
example2 0 = 0
example2 n = maximum $ map (n `mod`) [1..(abs n)]
Related
sumOfDigitsPosNeg x =
if x == 0 then 0
else if x < 0 then sumOfDigitsPosNeg ((-1)*x `div` 10) + mod ((-1)*x) 10
else sumOfDigitsPosNeg (x `div` 10) + mod x 10
I've tried with these code, but if the input is more than one digit, the output is wrong. I'm just confused how to convert the negative numbers into positive. How do I approach this problem?
Using abs this is quite easy. We just operate on the absolute value of the number input.
sumDigits :: Integral t => t -> t
sumDigits 0 = 0
sumDigits n = a `mod` 10 + sumDigits (a `div` 10)
where a = abs n
You can work with a helper go function that will only retrieve the absolute value. We thus call go with the abs :: Num a => a -> a of the item:
sumOfDigitsPosNeg :: Integral a => a -> a
sumOfDigitsPosNeg = go . abs
where go 0 = 0
go n = r + go q
where (q, r) = quotRem n 10
I need to determine a recursive function crosssum :: Int -> Int in Haskell to calculate the cross sum of positive numbers. I am not allowed to use any functions from the hierarchical library besides (:), (>), (++), (<), (>=), (<=), div, mod, not (&&), max, min, etc.
crosssum :: Int -> Int
cross sum x = if x > 0
then x `mod` 10
+ x `div` 10 + crosssum x
else 0
so whenever I fill in e.g. crosssum 12 it says 'thread killed'. I do not understand how to get this right. I would appreciate any ideas. Thx
One of the problems with your code is that x is not reduced (or changed somehow) when it's passed as an argument to the recursive call of crosssum. That's why your program never stops.
The modified code:
crosssum :: Int -> Int
crosssum x = if x > 0
then x `mod` 10 + crosssum (x `div` 10)
else 0
is going to have the following logic
crosssum 12 = 2 + (crosssum 1) = 2 + (1 + (crosssum 0)) = 2 + 1 + 0
By the way, Haskell will help you to avoid if condition by using pattern-matching to receive more readable code:
crosssum :: Int -> Int
crosssum 0 = 0
crosssum x =
(mod x 10) + (crosssum (div x 10))
divMod in Prelude is very handy, too. It's one operation for both div and mod, In fact for all 2 digit numbers dm n = sum.sequence [fst,snd] $ divMod n 10
cs 0 = 0; cs n = m+ cs d where (d,m) = divMod n 10
cs will do any size number.
I'm doing a simple Haskell function using recursion. At the moment, this seems to work but, if I enter 2, it actually comes up as false, which is irritating. I don't think the code is as good as it could be, so, if you have any advice there, that'd be cool too!
I'm pretty new to this language!
EDIT: Ok, so I understand what a prime number is.
For example, I want to be able to check 2, 3, 5, 7, etc and have isPrime return true. And of course if I run the function using 1, 4, 6, 8 etc then it will return false.
So, my thinking is that in pseudo code I would need to do as follows:
num = 2 -> return true
num > 2 && num = even -> return false
After that, I'm struggling to write it down in any working code so the code below is my work in process, but I really suck with Haskell so I'm going nowhere at the minute.
module Recursion where
isPrime :: Int -> Bool
isPrime x = if x > 2 then ((x `mod` (x-1)) /= 0) && not (isPrime (x-1)) else False
Ok,
let's do this step by step:
In math a (natural) number n is prime if it has exactly 2 divisors: 1 and itself (mind 1 is not a prime).
So let's first get all of the divisors of a number:
divisors :: Integer -> [Integer]
divisors n = [ d | d <- [1..n], n `mod` d == 0 ]
then get the count of them:
divisorCount :: Integer -> Int
divisorCount = length . divisors
and voila we have the most naive implementation using just the definition:
isPrime :: Integer -> Bool
isPrime n = divisorCount n == 2
now of course there can be quite some impprovements:
instead check that there is no divisor > 1 and < n
you don't have to check all divisors up to n-1, it's enough to check to the squareroot of n
...
Ok just to give a bit more performant version and make #Jubobs happy ;) here is an alternative:
isPrime :: Integer -> Bool
isPrime n
| n <= 1 = False
| otherwise = not . any divides $ [2..sqrtN]
where divides d = n `mod` d == 0
sqrtN = floor . sqrt $ fromIntegral n
This one will check that there is no divisor between 2 and the squareroot of the number
complete code:
using quickcheck to make sure the two definitions are ok:
module Prime where
import Test.QuickCheck
divisors :: Integer -> [Integer]
divisors n = [ d | d <- [1..n], n `mod` d == 0 ]
divisorCount :: Integer -> Int
divisorCount = length . divisors
isPrime :: Integer -> Bool
isPrime n
| n <= 1 = False
| otherwise = not . any divides $ [2..sqrtN]
where divides d = n `mod` d == 0
sqrtN = floor . sqrt $ fromIntegral n
isPrime' :: Integer -> Bool
isPrime' n = divisorCount n == 2
main :: IO()
main = quickCheck (\n -> isPrime' n == isPrime n)
!!warning!!
I just saw (had something in the back of my mind), that the way I did sqrtN is not the best way to do it - sorry for that. I think for the examples with small numbers here it will be no problem, but maybe you really want to use something like this (right from the link):
(^!) :: Num a => a -> Int -> a
(^!) x n = x^n
squareRoot :: Integer -> Integer
squareRoot 0 = 0
squareRoot 1 = 1
squareRoot n =
let twopows = iterate (^!2) 2
(lowerRoot, lowerN) =
last $ takeWhile ((n>=) . snd) $ zip (1:twopows) twopows
newtonStep x = div (x + div n x) 2
iters = iterate newtonStep (squareRoot (div n lowerN) * lowerRoot)
isRoot r = r^!2 <= n && n < (r+1)^!2
in head $ dropWhile (not . isRoot) iters
but this seems a bit heavy for the question on hand so I just remark it here.
Here are two facts about prime numbers.
The first prime number is 2.
An integer larger than 2 is prime iff it's not divisible by any prime number up to its square root.
This knowledge should naturally lead you to something like the following approach:
-- primes : the infinite list of prime numbers
primes :: [Integer]
primes = 2 : filter isPrime [3,5..]
-- isPrime n : is positive integer 'n' a prime number?
isPrime :: Integer -> Bool
isPrime n
| n < 2 = False
| otherwise = all (\p -> n `mod` p /= 0) (primesPrefix n)
where primesPrefix n = takeWhile (\p -> p * p <= n) primes
As a bonus, here is a function to test whether all items of a list of integers be prime numbers.
-- arePrimes ns : are all integers in list 'ns' prime numbers?
arePrimes :: [Integer] -> Bool
arePrimes = all isPrime
Some examples in ghci:
ghci> isPrime 3
True
ghci> isPrime 99
False
ghci> arePrimes [2,3,7]
True
ghci> arePrimes [2,3,4,7]
False
You can get a recursive formulation from the "2 divisors" variant by step-wise refinement:
isPrime n
= 2 == length [ d | d <- [1..n], rem n d == 0 ]
= n > 1 && null [ d | d <- [2..n-1], rem n d == 0 ]
= n > 1 && and [ rem n d > 0 | d <- takeWhile ((<= n).(^2)) [2..] ]
= n > 1 && g 2
where
g d = d^2 > n || (rem n d > 0 && g (d+1))
= n == 2 || (n > 2 && rem n 2 > 0 && g 3)
where
g d = d^2 > n || (rem n d > 0 && g (d+2))
And that's your recursive function. Convince yourself of each step's validity.
Of course after we've checked the division by 2, there's no need to try dividing by 4,6,8, etc.; that's the reason for the last transformation, to check by odds only. But really we need to check the divisibility by primes only.
I want to reverse an Integer in Haskell with recursion. I have a small issue.
Here is the code :
reverseInt :: Integer -> Integer
reverseInt n
| n>0 = (mod n 10)*10 + reverseInt(div n 10)
| otherwise = 0
Example 345
I use as input 345 and I want to output 543
In my program it will do....
reverseInt 345
345>0
mod 345 10 -> 5
reverseInt 34
34
34>0
mod 34 10 -> 4
reverseInt 3
3>0
mod 3 10 -> 3
reverseInt 0
0=0 (ends)
And at the end it returns the sum of them... 5+4+3 = 12.
So I want each time before it sums them, to multiple the sum * 10. So it will go...
5
5*10 + 4
54*10 + 3
543
Here's a relatively simple one:
reverseInt :: Int -> Int
reverseInt 0 = 0
reverseInt n = firstDigit + 10 * (reverseInt $ n - firstDigit * 10^place)
where
n' = fromIntegral n
place = (floor . logBase 10) n'
firstDigit = n `div` 10^place
Basically,
You take the logBase 10 of your input integer, to give you in what place it is (10s, 100s, 1000s...)
Because the previous calculation gives you a floating point number, of which we do not need the decimals, we use the floor function to truncate everything after the decimal.
We determine the first digit of the number by doing n 'div' 10^place. For example, if we had 543, we'd find place to be 2, so firstDigit = 543/100 = 5 (integer division)
We use this value, and add it to 10 * the reverse of the 'rest' of the integer, in this case, 43.
Edit: Perhaps an even more concise and understandable version might be:
reverseInt :: Int -> Int
reverseInt 0 = 0
reverseInt n = mod n 10 * 10^place + reverseInt (div n 10)
where
n' = fromIntegral n
place = (floor . logBase 10) n'
This time, instead of recursing through the first digit, we're recursing through the last one and using place to give it the right number of zeroes.
reverseInt :: Integer -> Integer
reverseInt n = snd $ rev n
where
rev x
| x>0 = let (a,b) = rev(div x 10)
in ((a*10), (mod x 10)*a + b)
| otherwise = (1,0)
Explanation left to reader :)
I don't know convenient way to found how many times you should multiply (mod n 10) on 10 in your 3rd line. I like solution with unfoldr more:
import Data.List
listify = unfoldr (\ x -> case x of
_ | x <= 0 -> Nothing
_ -> Just(mod x 10, div x 10) )
reverse_n n = foldl (\ acc x -> acc*10+x) 0 (listify n)
In listify function we generate list of numbers from integer in reverse order and after that we build result simple folding a list.
Or just convert it to a string, reverse it and convert it back to an integer:
reverseInt :: Integer -> Integer
reverseInt = read . reverse . show
More (not necessarily recursion based) answers for great good!
reverseInt 0 = 0
reverseInt x = foldl (\x y -> 10*x + y) 0 $ numToList x
where
numToList x = if x == 0 then [] else (x `rem` 10) : numToList (x `div` 10)
This is basically the concatenation of two functions : numToList (convert a given integer to a list 123 -> [1,2,3]) and listToNum (do the opposite).
The numToList function works by repeatedly getting the lowest unit of the number (using rem, Haskell's remainder function), and then chops it off (using div, Haskell's integer division function). Once the number is 0, the empty list is returned and the result concatenates into the final list. Keep in mind that this list is in reverse order!
The listToNum function (not seen) is quite a sexy piece of code:
foldl (\x y -> 10*x + y) 0 xs
This starts from the left and moves to the right, multiplying the current value at each step by 10 and then adding the next number to it.
I know the answer has already been given, but it's always nice to see alternative solutions :)
The first function is recursive to convert the integer to a list. It was originally reversing but the re-conversion function reversed easier so I took it out of the first. The functions can be run separately. The first outputs a tuple pair. The second takes a tuple pair. The second is not recursive nor did it need to be.
di 0 ls = (ls,sum ls); di n ls = di nn $ d:ls where (nn,d) = divMod n 10
di 3456789 []
([3,4,5,6,7,8,9],42)
rec (ls,n) = (sum [y*(10^x)|(x,y) <- zip [0..] ls ],n)
Run both as
rec $ di 3456789 []
(9876543,42)
My homework was to provide a function that computes 'x^y mod n' -for any n < (sqrt maxint32)
So I started by writing doing this:
modPow :: Int -> Int -> Int -> Int
modPow x y n = (x `mod` n) ^ (y `mod` n) `mod` n
Which seemed to work fine, for any number of n, although my next homework question involved using x^n mod n = x (Camichael numbers) and I could never get modPow to work.
So I made another modPow using pseudocode for mod exponentiation, -from wikipedia:
modPow2 :: Int -> Int -> Int -> Int
modPow2 x y n
= loopmod 1 1
where
loopmod count total = if count > y
then total
else loopmod (count+1) ((total*x) `mod` n)
Which now correctly produces the right answer for my next question, (x^n mod n = x) -for checking for Camichael numbers.
ALTHOUGH, modPow2 does not work for big numbers of 'y' (STACK-OVERFLOW!!)
How could I adjust modPow2 so it no longer gets a stackoverflow in the cases where y > 10,000 (but still less than sqrt of maxint 32 -which is around 46,000)
Or is there a fix on my original modPow so it works with x^n mod n = x? (I always do 560 561 561 as inputs and it gives me back 1 not 560 (561 is a carmichael number so should give 560 back)
Thanks alot.
Your formula for modPow is wrong, you can't just use y mod n as the exponent, it will lead to wrong results. For example:
Prelude> 2^10
1024
Prelude> 2^10 `mod` 10
4
Prelude> 2^(10 `mod` 10) `mod` 10
1
For a better modPow function you could use that x2n+1 = x2n ⋅ x and x2n = xn ⋅ xn and that for multiplication you actually can simply use the mod of the factors.
Where did you get your formula for modPow from?
(x ^ y) `mod` n = ((x `mod` n) ^ (y `mod` φ n)) `mod` n where φ is Euler's totient function.
This is probably because the argument total is computed lazily.
If you use GHC, you can make loopmod strict in total by placing a ! in frontof the argument, i.e.
loopmod count !total = ...
Another way would be to force evaluation of total like so: Replace the last line with
else if total == 0 then 0 else loopmod (count+1) ((total*x) `mod` n)
This does not change semantics (because 0*xis 0 anyway, so the reminder must be 0 also) and it forces hugs to evaluate total in every recursion.
If you are looking for implementation ( a^d mod n ) then
powM::Integer->Integer->Integer->Integer
powM a d n
| d == 0 = 1
| d == 1 = mod a n
| otherwise = mod q n where
p = powM ( mod ( a^2 ) n ) ( shiftR d 1 ) n
q = if (.&.) d 1 == 1 then mod ( a * p ) n else p