Checking If a Number is Special Prime - haskell

I am trying to create a program that prints special prime numbers in Haskell
isSpecialPrime :: Integer -> Bool . The function should return if a number is a special prime number or not. A special prime number is a prime number that can be written as the sum of two neighboring prime numbers and 1. An example for a special prime number is 19 = 7 + 11 + 1.
I have managed to check if a number is prime or not here :
isPrime :: Integer -> Bool
isPrime 1 = False
isPrime 2 = True
isPrime n
| (length [x | x <- [2 .. n-1], n `mod` x == 0]) > 0 = False
| otherwise = True
Any ideas to tweak the code to return only the Special Primes
The output put should be something similar to this
> isSpecialPrime 19
True

If you use an aux function, you can do it like:
isPrime :: Integer -> Bool
isPrime 1 = False
isPrime 2 = True
isPrime n
| (length [x | x <- [2 .. n-1], n `mod` x == 0]) > 0 = False
| otherwise = True
isSpecialPrime :: Integer -> Bool
isSpecialPrime 1 = False
isSpecialPrime x =
let firstNeighboring = findNeighbore x in
isSpecialPrime' x firstNeighboring
isSpecialPrime' :: Integer -> Integer -> Bool
isSpecialPrime' _ 0 = False
isSpecialPrime' p x =
let firstNeighboring = findNeighbore x in
let secondNeighboring = findNeighbore firstNeighboring in
if (1 + firstNeighboring + secondNeighboring) == p
then True
else isSpecialPrime' p firstNeighboring
findNeighbore 0 = 0
findNeighbore x = if isPrime (x-1) then x-1 else findNeighbore (x-1)
primes :: [Integer]
primes = sieve (2 : [3, 5..])
where
sieve (p:xs) = p : sieve [x|x <- xs, x `mod` p > 0]
As an example:
filter isSpecialPrime $ take 40 primes
=> [13,19,31,37,43,53,61,79,101,113,139,163,173]
A little optimization:
isSpecialPrime' :: Integer -> Integer -> Bool
isSpecialPrime' _ 1 = False
isSpecialPrime' p x =
let firstNeighboring = findNeighbore x in
let secondNeighboring = findNeighbore firstNeighboring in
let sumNeigh = secondNeighboring + firstNeighboring in
if (p `div` 3) > sumNeigh
then False else
if (1 + sumNeigh) == p
then True
else isSpecialPrime' p firstNeighboring
example:
filter isSpecialPrime $ take 100 primes
=> [13,19,31,37,43,53,61,79,101,113,139,163,173,199,211,223,241,269,277,331,353,373,397,457,463,509,521,541]

Related

Luhn algorithm implementation

I'm expecting luhn 5594589764218858 = True but it is always False
-- Get the last digit from a number
lastDigit :: Integer -> Integer
lastDigit 0 = 0
lastDigit n = mod n 10
-- Drop the last digit from a number
dropLastDigit :: Integer -> Integer
dropLastDigit n = div n 10
toRevDigits :: Integer -> [Integer]
toRevDigits n
| n <= 0 = []
| otherwise = lastDigit n : toRevDigits (dropLastDigit n)
-- Double every second number in a list starting on the left.
doubleEveryOther :: [Integer] -> [Integer]
doubleEveryOther [] = []
doubleEveryOther (x : []) = [x]
doubleEveryOther (x : y : z) = x : (y * 2) : doubleEveryOther z
-- Calculate the sum of all the digits in every Integer.
sumDigits :: [Integer] -> Integer
sumDigits [] = 0
sumDigits (x : []) = x
sumDigits (x : y) = (lastDigit x) + (dropLastDigit x) + sumDigits y
-- Validate a credit card number using the above functions.
luhn :: Integer -> Bool
luhn n
| sumDigits (doubleEveryOther (toRevDigits n)) `div` 10 == 0 = True
| otherwise = False
I know it can be done easier but I'm following a Haskell introductory. I think my only problem is in the luhn function. The course mentions problems may occur because toRevDigits reverses the number but I think it should work anyways.
The snippet x `div` 10 == 0 is not a correct check that x is divisible by ten; you should use `mod` instead. Also, this equation is incorrect:
sumDigits (x : []) = x
(Try, e.g. sumDigits [10].) It can be fixed, but deleting it is simpler and still correct.

Haskell - eliminate prime numbers from a list

I want to write a function wp (without primes) which removes all the primes from a list
of numbers. Thus, wp [1, 2, 3, 4, 5, 6, 7] = [1, 4, 6].
I tried coding it like this:
wp :: [Int] -> [Int]
prime :: Int -> Bool
prime n = if f n > 0 then False else True
where f n = foldl (\acc x -> if n `mod` x == 0 then acc = acc + 1 else acc = acc + 0) 0 [2..n-1]
wp xs = filter (not.prime) xs
But when compiling it, I get the "parse error on input =" error but I can't find my syntax error. Any ideas?
Your problem is in the use of acc = acc + x. You just need to write it as acc + 1 or acc + 0 (or just acc really) instead. Also, I would recommend writing the function signature on top of the function definition, rather than a C-style list at the top.
Finally, I should note that wp will not include 1 in the result, so you will have to manually include it.
prime :: Int -> Bool
prime n = if f n > 0 then False else True
where f n = foldl (\acc x -> if n `mod` x == 0 then acc + 1 else acc) 0 [2..n-1]
wp :: [Int] -> [Int]
wp xs = 1 : filter (not.prime) xs

Does the IO Monad evaluate lazily?

Here is the following code in which I try to found some prime divisors. I have tried to convert TAOCP algorithms to Haskell programs but I can understand when something evaluates lazily or eagerly:
modof2 n = let a0 = shiftR n 1
a1 = shiftL a0 1
in n-a1
iseven n = modof2 n == 0
factoringby2 n = let s=(lastf (takeWhile f [1..])) + 1
d=n `quot` powerof2 s
in (s,d)
where f s = let d = n `quot` (powerof2 s)
in if isodd d
then False
else True
lastf [] = 0
lastf xs = last xs
miller_rabin_prime_test n 0 result=return result
miller_rabin_prime_test n k result| (isodd n) && n>3 = do
a<-randomRIO(2,n-2)
let z = basic_step n a (fst sd) (snd sd)
miller_rabin_prime_test n (k-1) z
where sd=factoringby2 n
basic_step:: Integer->Integer->Int->Integer->Bool
basic_step n a s d =any (\x-> x==1 || x==n-1) (map x (map u [0..s-1]))
where u j=powerof2(j)*d
x j=modular_pow a j n 1
isprime n = if n==2 || n==3
then return True
else if n<2
then return False
else if iseven n
then return False
else miller_rabin_prime_test n 5 True
x_m :: Double->Integer->Integer
x_m 0 n = 2
x_m m n = f (x_m (m-1) n) `mod` n
where f x = x^2 +1
l::Double->Double
l m = 2 ^ (floor (log2 m))
where log2 m = log m / log 2
g m n = let a = x_m m n
b = x_m ((l m)-1) n
in gcd (a-b) n
gg n = [g m n|m<-[1..]]
algorithmB n = do
testprime<-isprime n
let a = head (filter (1>) (gg n))
c<-algorithmB (n `div` a)
if testprime
then return []
else return (a:c)
algorithmB does not terminate. Why this happens? I think that c<-algorithmB (n div a) is the reason because it does not evaluate lazily. Is that true?
Thanks
algorithmB calls itself in an infinite loop. Of course it doesn't return!

Get primes below x

I'm trying to write a procedure that returns a list of all primes below a given number.
For example:
Prelude>primes 8
[2,3,5,7]
When I try to load the file I get Parse error in pattern Failed, modules loaded: none. If someone could point me in the right direction I would be grateful.
primes :: Int -> [Int]
primes x < 2 = []
primes x | isPrime x == True = primes (x - 1) ++ x
| otherwise = primes (x - 1)
isPrime :: Int -> Bool
isPrime x | x < 2 = False
| x == 2 || x == 3 = True
| divEven x == True = False
| divOdd x 3 == True = False
| otherwise = True
divEven :: Int -> Bool
divEven x | mod x 2 == 0 = True
| otherwise = False
divOdd :: Int Int -> Bool
divOdd x num | mod x num == 0 == True
| num <= x/2 = divOdd x (num + 2)
| otherwise = False
A collection of small mistakes.
Your syntax is incorrect.
primes x < 2 = []
Probably you meant
primes x | x < 2 = []
Similarly, where you write
divOdd x num | mod x num == 0 == True
you probably meant
divOdd x num | mod x num == 0 = True
The type signature
divOdd :: Int Int -> Bool
is not valid. You probably meant
divOdd :: Int -> Int -> Bool
x is of type Int, and (/) :: Fractional a => a -> a -> a cannot be applied to it. You probably mean num <= x `div` 2 or 2 * num <= x.
divOdd :: Int Int -> Bool
divOdd x num | mod x num == 0 == True
| num <= x/2 = divOdd x (num + 2)
| otherwise = False
x is of type Int, not [Int]. (++) :: [a] -> [a] -> [a] will not apply to it.
primes x | isPrime x == True = primes (x - 1) ++ x
Perhaps you meant
primes x | isPrime x == True = primes (x - 1) ++ [x]
Finally, this is a fairly inefficient way of generating primes. Have you considered a sieve? Prime numbers - HaskellWiki may be a bit difficult for you right now, but shows many different strategies.
Here's a re-write of your functions using list comprehensions (also in Wikipedia), perhaps this is more visually apparent:
primes :: Int -> [Int]
primes x | x<2 = []
| x<4 = [2..x]
| True = primes (x-1) ++ [x | isPrime x]
your isPrime is
isPrime x = x > 1 &&
( x < 4 ||
and [ rem x n /= 0 | n <- 2 : [3,5..(div x 2)+2] ] )
and is a function defined in standard Prelude. It will test entries in a list, left to right, to see if all are True. It will stop on the first False entry encountered, so the rest of them won't get explored.
Sometimes when the code is more visually apparent it is easier to see how to improve it.

Haskell. Numbers in binary numbers. words

import Data.Char
blockCode :: S
lett2num :: Char -> Int
lett2num y
| (or
num2bin :: Int -> [Int]
num2bin n: negative number"
where n2b 0 = []
n2b n = n `mod` 2 : n2b (n `div` 2)
You can use concatMap show to transform a list into a string:
Main> num2bin 8
[0,0,0,1]
Main> concatMap show $ num2bin 8
"0001"
but note that your function's output is reversed.
To do everything in one go, do
num2bin :: Int -> String
num2bin n
| n >= 0 = concatMap show $ reverse $ n2b n
| otherwise = error "num2bin: negative number"
where n2b 0 = []
n2b n = n `mod` 2 : n2b (n `div` 2)
Function converts integer to binary:
num2bin :: (Integral a, Show a) => a -> String
num2bin 0 = "0"
num2bin 1 = "1"
num2bin n
| n < 0 = error "Negative number"
| otherwise = num2bin (n `div` 2) ++ show (n `mod` 2)

Resources