The task is to generate list with numbers, whose digits are only 2,4,6.
Example:[2,4,6,22,24,26,42,44,46,62,64,66,222,224,226,...]
I have already solved this task via brute force:
numberHasOnly246 :: Integer -> Bool
numberHasOnly246 0 = False
numberHasOnly246 n = result
where
result = helper True (abs n)
helper :: Bool -> Integer -> Bool
helper result n
| (div n 10 == 0) = condition && result
| (div n 10 > 0) = helper (condition && result) (div n 10)
where
condition = mod n 10 == 4 || mod n 10 == 6 || mod n 10 == 2
series246 :: [Integer]
series246 = numbers[1..]
where
numbers(e : ls) = e : (numbers [ x | x <- ls, (numberHasOnly246 x == True)])
But it seems that this solution is too slow.
Also, I've read, that there is tying the knot method for generating infinite lists in Haskell, but here I cannot find how to solve it via tying the knot. Is this method suitable here?
Instead of a generate-and-test approach, you can only generate numbers that are valid.
For a single digit this is thus:
digits :: [Int]
digits = [2, 4, 6]
for numbers, we can make use of recursion here:
numbers = [ 10*t + d | t <- (0:numbers), d <- digits ]
Here t is thus the values we multiply with 10, and we start with 0. d are the digits that we then can append. This thus gives us:
Prelude> numbers
[2,4,6,22,24,26,42,44,46,62,64,66,222,224,226,242,244,246,262,264,266,422,424,426,442, …
Related
Hi I am new to haskell and I was just wondering whether it was possible to store a value that has already been removed:
This is my code
input :: Integer -> String
input x = checklength $ intolist x
intolist 0 = []
intolist x = intolist (x `div` 10) ++ [x `mod` 10]
checklength x = if length(x) >= 13 && length(x) <= 16 then doubleall
(init(x)) else "Not valid length of credit card number"
doubleall x = finalcheck $ final $ double (reverse (x))
double x = case x of
[] -> []
[x] -> if (x*2 < 10) then [x*2] else [x*2 `div` 10 + x*2 `mod` 10]
x:y:xs -> (if (x*2 < 10) then [x*2] else [x*2 `div` 10 + x*2 `mod` 10]) ++
y:double xs
final x = (sum x) * 9
finalcheck x = if (x `mod` 10 == ...... ) then "True" else "False"
My code basically takes an input as an integer such as 987564736264535. then makes this integer into a list of number such as [9,8,7..5]. Then it checks the length has to between 13 to 16 digits. If not you get an error statement. If the digits are between the required amount it will go into the doubeall function and remove the last number using (init). the number removed is 5 in which it will double the numbers and reverse the list order. It will then sum the numbers together and multiple by 9. The final step that I have done part of is taking the last digit of the number that has already been summed together and multiplied by 9. So lets give and example lets say I get 456 then I use mod 10 to take the last number which is 6. **Now here is where I am having a problem in which I want to check whether this 6 is equal to the same number that was removed originally in the checklength function when I used init. So in the checklength function I removed the number 5 **
Thanks
Once you remove data, you can't access it again. You need a function that preserves the final checkdigit that you're stripping off.
Since order is (mostly) irrelevant, consider:
validate :: Integer -> Bool
validate x = let digits = toDigits x
in if checkLength digits
then doesMatch . splitCheckdigit $ digits
else False
where
toDigits 0 = [0]
toDigits x = go x
where
go 0 = []
go x = let (d, m) = x `divMod` 10
in m : toDigits d
-- reverses order
checkLength x = let l = length x
in 13 <= l && l <= 16
splitCheckdigit (checkdigit:rest) = (checkdigit, rest)
-- remember we reversed in toDigits, so the *first* digit is the checkdigit!
doesMatch (checkdigit, rest) = let total = (*9) . sum . reduce $ rest
shouldBe = total `mod` 10
in checkdigit == shouldBe
where
reduce (x:y:xs) = (sum . toDigits $ x) : y : reduce xs
reduce [x] = [sum . toDigits $ x]
reduce [] = []
-- note how #toDigits# is reused here rather than redefined.
If you prefer Arrows, validate can be written as:
toDigits >>> ((doesMatch <<< splitCheckdigit) &&& checkLength) >>> uncurry (&&)
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)
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)]
I need to implement a recursive function that returns 1 if the number is prime or 0 otherwise. The homework problem says that I can't use '%' mod. Haskell should be something like this... I'm not sure.
isprime x = prime(x sqrt(x))
prime x i = | i==1 = 1
| mod(x i)==0 = 0
| otherwise = prime(x i-1)
mod num div | num<div = n
| otherwise = mod(num-div div)
I tested an algorithm in C because I don't have a Haskell compiler on my Mac, but there's something wrong because it's returning false positive on primes-1. idk why.
int main (int argc, const char * argv[]){
int a=0,b=31;
printf("\n Prime numbers between %d and %d \n",a,b);
for(int a=0; a<=b; a++){
if(isPrime(a)==0){
printf("%d, ",a);
}
}
return 0;
}
int isPrime(int x){
return prime(x, sqrt(x));
}
int prime(int x, int i){
if(i==0){
return 0;
}
else if(mod(x,i)==1){
return 1;
}
else{
return prime(x, i-1);
}
}
int mod(int num, int div){
if(num<div) return num;
else return mod(num-div, div);
}
The algorithm is returning this:
Prime numbers between 0 and 31
0, 1, 2, 3, 4, 6, 8, 12, 14, 18, 20, 24, 30,
Program ended with exit code: 0
Your basic idea is fine. In Haskell you can use lists instead of iteration. Here's what you need to look into:
Install and play with ghci.
If you have no idea how to do anything in Haskell, visit Learn You a Haskell for Great Good http://learnyouahaskell.com/
List comprehensions. Lean what [n^2 | n <- [1..10]] means and play with similar lists.
Look up functions like sqrt on hoogle http://www.haskell.org/hoogle/
Because Haskell is statically typed you will need to convert some numerical types between Integer and Float. Look up Float -> Integer and Integer -> Float when you do. DON'T use unsafeCoerce - it's unsafe and will break things badly.
Use hoogle to look up [Bool] -> Bool. Why did I suggest that? How would [Bool] help, and how would you make one anyway? (Revise list comprehension again.)
Come back with more specific questions once you've found out more and had a go.
Always start your assignments early, especially if you've missed classes!
You were set this homework not because the department was stuck for a way of deciding whether 102659473841923461 is prime, but because they want you to learn some Haskell. Try not to try to solve the problem without doing the learning - it'll only make the next assignment even harder! (This is why I've resisted the temptation to translate the "pseudocode" in another answer into Haskell.)
(apparently, there's a new policy regarding homework, viz. "If you don't want a fully vetted, complete and testable answer, Stack Overflow is not the place to ask - by Tim Post", so here goes).
Basically, your code is almost correct (1 is not a prime), sans some syntax issues.
isprime x = prime x (floor $ sqrt $ fromIntegral x) where
prime x i | i==1 && x > 1 = 1
| x == i*div x i = 0
| otherwise = prime x (i-1)
-- mod x i = x - i*div x i
-- mod x i == 0 = x == i*div x i
fromIntegral is just some adaptor which lets us use an Integral value as an argument to sqrt which expects a Floating argument. Try using :i sqrt or :i Integral etc. at the GHCi prompt (also read some documentation google around).
But algorithmically there's place for improvement. First of all, it's much better to try out the divisors in the other direction, from 2 up to the number's sqrt, because any given number is more likely to have a smaller factor than a larger one. Second, after trying out 2, there's no need to try out any other even number as a possible divisor. This gives us
isprime x | x == 2 = 1
| x < 2 || even x = 0
| otherwise = go 3
where
r = floor $ sqrt $ fromIntegral x
go i | i > r = 1
| x == i*div x i = 0 -- really, | rem x i == 0 = 0
| otherwise = go (i+2)
This would normally be written down using Bools, and a higher-order function like and which captures the recursions and testing pattern (so it is not recursive anymore):
isprime x = if isPrime x then 1 else 0
isPrime x = x==2 || x>2 && odd x &&
and [rem x d /= 0 | d <- [3,5..floor $ sqrt $ fromIntegral x]]
There's some redundancy in there still: after we've tested by 3, there's no need to test by any of its multiples too (just like we did with 2 and evens). We really just need to test by prime factors:
isPrime x = x>1 && and
[rem x d /= 0 | d <- takeWhile (<= (floor $ sqrt $ fromIntegral x)) primes]
primes = filter isPrime [2..]
= 2 : filter isPrime ([3..] `minus` [4,6..])
= 2 : filter isPrime [3,5..]
= 2 : 3 : filter isPrime ([5,7..] `minus` [9,15..])
= 2 : 3 : 5 : filter isPrime (([7,9..]`minus`[9,15..])`minus`[25,35..])
...........
Here we see the emergence of the sieve of Eratosthenes, P = {3,5, ...} \ U {{p2, p2 + 2p, ...} | p in P} (w/out the 2).
see also:
http://en.wikipedia.org/wiki/Haskell_features#Prime_numbers
http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
http://www.haskell.org/haskellwiki/Prime_numbers
I don't know Haskell, and I don't want to hand you the answer, but I can offer a method.
if you check all the numbers from 2 to sqrt(n), and none of them are factors of n, then n is prime.
So maybe a function call with the following pseudo code might work:
def isPrime(n):
return isPrimeHelper(n,sqrt(n))
def isPrimeHelper(n,counter):
if counter == 1 return True
if n % counter == 0 return False
else return isPrime(n,counter-1)