Write a function called factor that will take an Integer and determine its prime factors (called prime factorization). The function should take an integer and return a list of integers. This list should be the prime factors of the number, not including multiplicity. For example, the prime factors of 56 are 2 and 7 (even though the full multiplication is 56 = 23 × 7 = 2 × 2 × 2 × 7). What are the prime factors of 175561 and 62451532000?
So far, what I got is:
factor :: Int -> [Int]
factor n
| factors == [] = [n]
| otherwise = (factors ++ factor (n `div` (head factors)))
where factors = take 1 $ filter (\x -> (n `mod` x) == 0) [2 .. n-1]
but this print the full multiplication, when plug 56 it gives 2.2.2.7 and I want it with no duplication like 2, 7.
How can I filter?
Use nub :: Eq a => [a] -> [a], which removes duplicate elements from lists.
http://hackage.haskell.org/package/base-4.9.0.0/docs/Data-List.html#v:nub
Related
--for number divisible by 15 we can get it easily
take 10 [x | x <- [1..] , x `mod` 15 == 0 ]
--but for all how do I use the all option
take 10 [x | x <- [1..] , x `mod` [2..15] == 0 ]
take 10 [x | x <- [1..] , all x `mod` [2..15] == 0 ]
I want to understand how to use all in this particular case.
I have read Haskell documentation but I am new to this language coming from Python so I am unable to figure the logic.
First you can have a function to check if a number is mod by all [2..15].
modByNumbers x ns = all (\n -> x `mod` n == 0) ns
Then you can use it like the mod function:
take 10 [x | x <- [1..] , x `modByNumbers` [2..15] ]
Alternatively, using math, we know that the smallest number divible by all numbers less than n is the product of all of the prime numbers x less than n raised to the floor of the result of logBase x n.
A basic isPrime function:
isPrime n = length [ x | x <- [2..n], n `mod` x == 0] == 1
Using that to get all of the primes less than 15:
p = [fromIntegral x :: Float | x <- [2..15], isPrime x]
-- [2.0,3.0,5.0,7.0,11.0,13.0]
Now we can get the exponents:
e = [fromIntegral (floor $ logBase x 15) :: Float | x <- p']
-- [3.0,2.0,1.0,1.0,1.0,1.0]
If we zip these together.
z = zipWith (**) p e
-- [8.0,9.0,5.0,7.0,11.0,13.0]
And then find the product of these we get the smallest number divisible by all numbers between 2 and 15.
smallest = product z
-- 360360.0
And now to get the rest we just need to multiply that by the numbers from 1 to 15.
map round $ take 10 [smallest * x | x <- [1..15]]
-- [360360,720720,1081080,1441440,1801800,2162160,2522520,2882880,3243240,3603600]
This has the advantage of running substantially faster.
Decompose the problem.
You already know how to take the first 10 elements of a list, so set that aside and forget about it. There are infinitely many numbers divisible by all of [2,15], your remaining task is to list them all.
There are infinitely many natural numbers (unconstrained), and you already know how to list them all ([1..]), so your remaining task is to transform that list into the "sub-list" who's elements are divisible by all of [2,15].
You already know how to transform a list into the "sub-list" satisfying some constraint (predicate :: X -> Bool). You're using a list comprehension in your posted code, but I think the rest of this is going to be easier if you use filter instead. Either way, your remaining task is to represent "is divisible by all of [2,15]" as a predicate..
You already know how to check if a number x is divisible by another number y. Now for something new: you want to abstract that as a predicate on x, and you want to parameterize that predicate by y. I'm sure you could get this part on your own if asked:
divisibleBy :: Int -> (Int -> Bool)
divisibleBy y x = 0 == (x `mod` y)
You already know how to represent [2,15] as [2..15]; we can turn that into a list of predicates using fmap divisibleBy. (Or map, worry about that difference tomorrow.) Your remaining task is to turn a list of predicates into a predicate.
You have a couple of options, but you already found all :: (a -> Bool) -> [a] -> Bool, so I'll suggest all ($ x). (note)
Once you've put all these pieces together into something that works, you'll probably be able to boil it back down into something that looks a little bit like what you first wrote.
I'm looking for a non-recursive implementation of sum of digits (a "cross sum") of a non-negative number like this:
cs :: Int -> Int
cs n = sum digits_of_n where digits_of_n = [ . | ... ]
Basically: How does one get a list of digits from a non-negative whole number using list comprehension only?
A cross sum example: The crossum of 157 is 1 + 5 + 7 = 13
The "usual way" would be extracting the digits from a number recursively using modulo and division, and then summing them up like this:
cs :: Int -> Int
cs n = if n == 0 then 0 else n `mod` 10 + cs (n `div` 10)
I have however difficulty expressing this without recursion and with list comprehension, does anyone have ideas regarding this?
sume n = foldr (+) 0 [ digitToInt c | c <- show n, isDigit c ]
I need to find all the twin primes up to an inputted number. After my trying it out this is the closest i can get:
primeTwins :: Integer -> [Integer]
primeTwins x = [y | x <- [2..x], y <- [x-2, x+2]]
If x is 20 prime Twins returns: [0,4,1,5,3,7,5,9,9,13,11,15,15,19,17,21]
So this returns primes +2 and primes -2 and with duplicates, However i need just twin primes (A twin prime is a prime number that is either 2 less or 2 more than another prime number) with no duplication. Ive been searching but cant find a way to sort lists. Im very new to haskell, So any help would be appreciated!
First of all, it'd be nice to have an infinite list of primes:
primes :: [Integer]
primes = 2:3:filter
(\n -> not $ any
(\p -> n `mod` p == 0)
(takeWhile (\p -> p * p <= n) primes))
[5,7..]
This is similar to the Sieve of Eratosthenes, checking only prime factors up to the square root of the number. For reference, take 20 primes is [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71], so it works properly. Now, we want to filter out just the twin primes into another infinite list:
infTwinPrimes :: [Integer]
-- we need to manually enter 3 5 7 since 5 is a part of two pairs
infTwinPrimes = 3:5:7:(
-- we convert the tuple into a list
( >>= \(a, b) -> [a, b])
$ filter (\(a, b) -> b - a == 2)
-- we drop 4 to compensate for manually entering 3, 5, 7
$ drop 4
-- we zip primes with its tail in order to
-- get every element in a tuple with the next element
$ zip primes (tail primes)
)
If you're confused, it might help to think about how zip primes (tail primes) is [(2,3),(3,5),(5,7),(7,11),(11,13),(13,17),(17,19),...], and how [(1, 2), (3, 4)] >>= \(a, b) -> [a, b] is [1, 2, 3, 4]. Now, our twin primes function is as easy as a takeWhile:
twinPrimes :: Integer -> [Integer]
twinPrimes n = takeWhile (<= n) infTwinPrimes
And we can verify that it works
λ> twinPrimes 20
[3,5,7,11,13,17,19]
Which does indeed contain every twin prime up to 20.
This question already has answers here:
Enumerate factors of a number directly in ascending order without sorting?
(4 answers)
Making a list of divisors without dividing sequentially in Haskell
(3 answers)
Closed 3 years ago.
I want to efficiently find the proper divisors of an integer n.
How can I do this?
For now I´m using the following function
divisors :: (Integral a) => a -> [a]
divisors n = filter ((0 ==) . (n `mod`)) [1 .. (n `div` 2)]
But I have read that it is more efficient when I only check for the numbers until the square root of n. Have you got any suggestions how to solve it with the square root?
Given a number n is dividable by k, then n/k is a divisor of n as well. Indeed, since n/(n/k)=k. If k>√n, we thus know that k/n<√n, and therefore, instead of calculating all the divisors, we can each time we find a divisor, yield the "co-divisor" as well.
We thus can implement the algorithm as follows:
divisors :: Integral a => a -> [a]
divisors n = concatMap f (filter ((==) 0 . mod n) (takeWhile (\k -> k*k <= n) [1 .. n]))
where f k | k < l = [k, l]
| otherwise = [k]
where l = div n k
Here we thus first use takeWhile (\k -> k*k <= n) [1 .. n] to create a list from 1 until (and including if it is integral) √n).
Next we filter these elements, and only retain those that divide n. Finally for each of these elements, we check if the co-divisor is different. If that is the case, we both yield k and the co-divisor l, otherwise (this will only be the case for √n), we only yield k.
For example:
Prelude Data.List> divisors 1425
[1,1425,3,475,5,285,15,95,19,75,25,57]
I am trying to write a function in Haskell that allows me to calculate the next 3 prime numbers, given a Intenger N and store the three prime numbers in a sorted list.
The challenge is to do it without import any external module.
Behavior of the function:
*nextPrimes 75 = [79,83,89]
*nextPrimes 64 = [67,71,73]
it should calculate the next 3 prime numbers of an N with 10-digit numbers in less than 2 minutes.
nextPrimes :: Int -> [Int]
nextPrimes n
sorry... but I could not resist...
nextPrimes :: Int -> [Int]
nextPrimes n = let sq = fromIntegral . ceiling . sqrt $ fromIntegral n
pri k = (k,and [ k`mod`x/=0 | x <- [2..sq]])
in take 3 . map fst . filter snd $ map pri [n..]
This works almost instantly, even when we have to count up all the way until sqrt n:
λ> nextPrimes 295084709089
[295084709159,295084709209,295084709273]