I was trying to implement various forms of queries on Hailstone Sequence.
Hailstone sequences are sequences of positive integers with the following properties:
1 is considered the terminating value for a sequence.
For any even positive integer i, the value that comes after i in the sequence is i/2.
For any odd positive integer j > 1, the value that comes after j in the sequence is 3j+1
Queries can be
hailSequence(Seed,Sequence): where the Sequence is the hailstone sequence generated from the given Seed.
hailStone(M,N): where N is the number that follows M in a hailstone sequence. E.g. if M is 5 then N should be 16, if M is 20 then N should be 10, etc.
hailStorm(Seed,Depth,HailTree): where HailTree is the tree of values that could preceed Seed in a sequence of the specified depth.
Example:
| ?- hailStorm(1,4,H).
H = hs(1,hs(2,hs(4,hs(8)))) ?
yes
| ?- hailStorm(5,3,H).
H = hs(5,hs(10,hs(3),hs(20))) ?
yes
Pictorial Representation
Now I've implemented the first two predicates:
hailSequence(1,[1]) :- !.
hailSequence(N,[N|S]) :- 0 is N mod 2, N1 is round(N / 2), hailSequence(N1,S).
hailSequence(N,[N|S]) :- 1 is N mod 2, N1 is (3 * N) + 1, hailSequence(N1, S).
hailStone(X,Y) :- nonvar(X), 0 is X mod 2, Y is round(X / 2).
hailStone(X,Y) :- nonvar(X), 1 is X mod 2, Y is (3 * X) + 1.
hailStone(X,Y) :- nonvar(Y), 1 is Y mod 3, T is round( (Y - 1) / 3), 1 is T mod 2, X is T.
For the hailStorm/2 predicate, I've written the following code, but it is not working as expected:
make_hs1(S,hs(S)).
make_hs2(S,R,hs(S,make_hs1(R,_))).
make_hs3(S,L,R,hs(S,make_hs1(L,_),make_hs1(R,_))).
hailStorm(S,1,hs(S)) :- !.
hailStorm(S,D,H) :- nonvar(S), nonvar(D), 4 is S mod 6, S=\= 4, make_hs3(S,hailStorm(round((S-1)/3),D-1,_X),hailStorm(2*S,D-1,_Y),H).
hailStorm(S,D,H) :- nonvar(S), nonvar(D), make_hs2(S,hailStorm(2*S,D-1,_X),H).
Output:
| ?- hailStorm(5,2,H).
H = hs(5,make_hs1(hailStorm(2*5,2-1,_),_))
yes
which is not the desired output,i.e.,
H = hs(5,hs(10)) ?
There are several issues expressed in the problem statement:
In Prolog, there are predicates and terms but not functions. Thinking of them as functions leads one to believe you can write terms such as, foo(bar(3), X*2)) and expect that Prolog will call bar(3) and evaluate X*2 and then pass these results as the two arguments to foo. But what Prolog does is pass these just as terms as you see them (actually, X*2 internally is the term, *(X,2)). And if bar(3) were called, it doesn't return a value, but rather either succeeds or fails.
is/2 is not a variable assignment operator, but rather an arithmetic expression evaluator. It evaluates the expression in the second argument and unifies it with the variable or atom on the left. It succeeds if it can unify and fails otherwise.
Although expressions such as 0 is N mod 2, N1 is round(N / 2) will work, you can take more advantage of integer arithmetic in Prolog and write it more appropriately as, 0 =:= N mod 2, N1 is N // 2 where =:= is the arithmetic comparison operator. You can also use bit operations: N /\ 1 =:= 0, N1 is N // 2.
You haven't defined a consistent definition for what a hail storm tree looks like. For example, sometimes your hs term has one argument, and sometimes it has three. This will lead to unification failures if you don't explicitly sort it out in your predicate hailStorm.
So your hailSequence is otherwise correct, but you don't need the cut. I would refactor it a little as:
hail_sequence(1, [1]).
hail_sequence(Seed, [Seed|Seq]) :-
Seed > 1,
Seed /\ 1 =:= 0,
S is Seed // 2,
hail_sequence(S, Seq).
hail_sequence(Seed, [Seed|Seq]) :-
Seed > 1,
Seed /\ 1 =:= 1,
S is Seed * 3 + 1,
hail_sequence(S, Seq).
Or more compactly, using a Prolog if-else pattern:
hail_sequence(1, [1]).
hail_sequence(Seed, [Seed|Seq]) :-
Seed > 1,
( Seed /\ 1 =:= 0
-> S is Seed // 2
; S is Seed * 3 + 1
),
hail_sequence(S, Seq).
Your description for hailStone doesn't say it needs to be "bidirectional" but your implementation implies that's what you wanted. As such, it appears incomplete since it's missing the case:
hailStone(X, Y) :- nonvar(Y), Y is X * 2.
I would refactor this using a little CLPFD since it will give the "bidirectionality" without having to check var and nonvar. I'm also going to distinguish hail_stone1 and hail_stone2 for reasons you'll see later. These represent the two ways in which a hail stone can be generated.
hail_stone(S, P) :-
hail_stone1(S, P) ; hail_stone2(S, P).
hail_stone1(S, P) :-
S #> 1,
0 #= S rem 2,
P #= S // 2.
hail_stone2(S, P) :-
S #> 1,
1 #= S rem 2,
P #= S * 3 + 1.
Note that S must be constrained to be > 1 since there is no hail stone after 1. If you want these using var and nonvar, I'll leave that as an exercise to convert back. :)
Now to the sequence. First, I would make a clean definition of what a tree looks like. Since it's a binary tree, the common representation would be:
hs(N, Left, Right)
Where Left and Right are branchs (sub-trees), which could have the value nul, n, nil or whatever other atom you wish to represent an empty tree. Now we have a consistent, 3-argument term to represent the tree.
Then the predicate can be more easily defined to yield a hail storm:
hail_storm(S, 1, hs(S, nil, nil)). % Depth of 1
hail_storm(S, N, hs(S, HSL, HSR)) :-
N > 1,
N1 is N - 1,
% Left branch will be the first hail stone sequence method
( hail_stone1(S1, S) % there may not be a sequence match
-> hail_storm(S1, N1, HSL)
; HSL = nil
),
% Right branch will be the second hail stone sequence method
( hail_stone2(S2, S) % there may not be a sequence match
-> hail_storm(S2, N1, HSR)
; HSR = nil
).
From which we get, for example:
| ?- hail_storm(10, 4, Storm).
Storm = hs(10,hs(20,hs(40,hs(80,nil,nil),hs(13,nil,nil)),nil),hs(3,hs(6,hs(12,nil,nil),nil),nil)) ? ;
(1 ms) no
If you want to use the less symmetrical and, arguably, less canonical definition of binary tree:
hs(N) % leaf node
hs(N, S) % one sub tree
hs(N, L, R) % two sub trees
Then the hail_storm/3 predicate becomes slightly more complex but manageable:
hail_storm(S, 1, hs(S)).
hail_storm(S, N, HS) :-
N > 1,
N1 is N - 1,
( hail_stone1(S1, S)
-> hail_storm(S1, N1, HSL),
( hail_stone2(S2, S)
-> hail_storm(S2, N1, HSR),
HS = hs(S, HSL, HSR)
; HS = hs(S, HSL)
)
; ( hail_stone2(S2, S)
-> hail_storm(S2, N1, HSR),
HS = hs(S, HSR)
; HS = hs(S)
)
).
From which we get:
| ?- hail_storm1(10, 4, Storm).
Storm = hs(10,hs(20,hs(40,hs(80),hs(13))),hs(3,hs(6,hs(12)))) ? ;
no
Related
How to find generators of a finite field Fp[x]/f(x) with f(x) is a irreducible polynomial over Fp.
Input: p (prime number), n (positive number), f (irreducible polynomial)
Output: g (generator)
I have p = 2, n =3, f = x^3 + x + 1
I am a newbie so I don't know where to start.
Do you have any solution? Plese help me step by step
To find a generator (primitive element) α(x) of a field GF(p^n), start with α(x) = x + 0, then try higher values until a primitive element α(x) is found.
For smaller fields, a brute force test to verify that powers of α(x) will generate every non-zero number of a field can be done.
cnt = 0
m = 1
do
cnt = cnt + 1
m = (m*α)%f(x)
while (m != 1)
if cnt == (p^n-1) then α(x) is a generator for GF(p^n).
For a faster approach with larger fields, find all prime factors of p^n-1. Let q = any of those prime factors. If α(x) is a generator for GF(p^n), then while operating in GF(p^n):
α(x)^(p^n-1) % f(x) == 1
α(x)^((p^n-1)/q) % f(x) != 1, for all q that are prime factors of p^n-1
In this case GF(2^3) is a 3 bit field and since 2^3-1 = 7, which is prime, then it's just two tests, shown in hex: x^3 + x + 1 = b (hex)
α(x)^7 % b == 1
α(x)^1 % b != 1
α(x) can be any of {2,3,4,5,6,7} = {x,x+1,x^2,...,x^2+x+1}
As another example, consider GF(2^4), f(x) = x^4 + x^3 + x^2 + x + 1 (hex 1f). The prime factors of 2^4-1 = 15 are 3 and 5, and 15/3 = 5 and 15/5 = 3. So the three tests are:
α(x)^f % 1f == 1
α(x)^5 % 1f != 1
α(x)^3 % 1f != 1
α(x) can be any of {3,5,6,7,9,a,b,e}
For larger fields, finding all prime factors of p^n-1 requires special algorithms and big number math. Wolfram alpha can handle up to around 2^128-1:
https://www.wolframalpha.com/input/?i=factor%282%5E64-1%29
This web page can factor large numbers and includes an explanation and source code:
https://www.alpertron.com.ar/ECM.HTM
To test for α(x)^(large number) = 1 or != 1, use exponentiation by repeated squaring while performing the math in GF(p^n).
https://en.wikipedia.org/wiki/Exponentiation_by_squaring
For large fields, where p^n is greater than 2^32 (4 billion), a primitive polynomial where α(x) = x is searched for, using the test mentioned above.
Im pretty much new to Haskell, so if Im missing key concept, please point it out.
Lets say we have these two functions:
fact n
| n == 0 = 1
| n > 0 = n * (fact (n - 1))
The polymorphic type for fact is (Eq t, Num t) => t -> t Because n is used in the if condition and n must be of valid type to do the == check. Therefor t must be a Number and t can be of any type within class constraint Eq t
fib n
| n == 1 = 1
| n == 2 = 1
| n > 2 = fib (n - 1) + fib (n - 2)
Then why is the polymorphic type of fib is (Eq a, Num a, Num t) => a -> t?
I don't understand, please help.
Haskell always aims to derive the most generic type signature.
Now for fact, we know that the type of the output, should be the same as the type of the input:
fact n | n == 0 = 1
| n > 0 = n * (fact (n - 1))
This is due to the last line. We use n * (fact (n-1)). So we use a multiplication (*) :: a -> a -> a. Multiplication thus takes two members of the same type and returns a member of that type. Since we multiply with n, and n is input, the output is of the same type as the input. Since we use n == 0, we know that (==) :: Eq a => a -> a -> Bool so that means that that input type should have Eq a =>, and furthermore 0 :: Num a => a. So the resulting type is fact :: (Num a, Eq a) => a -> a.
Now for fib, we see:
fib n | n == 1 = 1
| n == 2 = 1
| n > 2 = fib (n - 1) + fib (n - 2)
Now we know that for n, the type constraints are again Eq a, Num a, since we use n == 1, and (==) :: Eq a => a -> a -> Bool and 1 :: Num a => a. But the input n is never directly used in the output. Indeed, the last line has fib (n-1) + fib (n-2), but here we use n-1 and n-2 as input of a new call. So that means we can safely asume that the input type and the output type act independently. The output type, still has a type constraint: Num t: this is since we return 1 for the first two cases, and 1 :: Num t => t, and we also return the addition of two outputs: fib (n-1) + fib (n-2), so again (+) :: Num t => t -> t -> t.
The difference is that in fact, you use the argument directly in an arithmetic expression which makes up the final result:
fact n | ... = n * ...
IOW, if you write out the expanded arithmetic expression, n appears in it:
fact 3 ≡ n * (n-1) * (n-2) * 1
This fixes that the argument must have the same type as the result, because
(*) :: Num n => n -> n -> n
Not so in fib: here the actual result is only composed of literals and of sub-results. IOW, the expanded expression looks like
fib 3 ≡ (1 + 1) + 1
No n in here, so no unification between argument and result required.
Of course, in both cases you also used n to decide how this arithmetic expression looks, but for that you've just used equality comparisons with literals, whose type is not connected to the final result.
Note that you can also give fib a type-preservig signature: (Eq a, Num a, Num t) => a -> t is strictly more general than (Eq t, Num t) => t -> t. Conversely, you can make a fact that doesn't require input- and output to be the same type, by following it with a conversion function:
fact' :: (Eq a, Integral a, Num t) => a -> t
fact' = fromIntegral . fact
This doesn't make a lot of sense though, because Integer is pretty much the only type that can reliably be used in fact, but to achieve that in the above version you need to start out with Integer. Hence if anything, you should do the following:
fact'' :: (Eq t, Integral a, Num t) => a -> t
fact'' = fact . fromIntegral
This can then be used also as Int -> Integer, which is somewhat sensible.
I'd recommend to just keep the signature (Eq t, Num t) => t -> t though, and only add conversion operations where it's actually needed. Or really, what I'd recommend is to not use fact at all – this is a very expensive function that's hardly ever really useful in practice; most applications that naïvely end up with a factorial really just need something like binomial coefficients, and those can be implemented more efficiently without a factorial.
I wrote this mips code to find the gcf but I am confused on getting the number of instructions executed for this code. I need to find a linear function as a function of number of times the remainder must be calculated before an answer. i tried running this code using Single step with Qtspim but not sure on how to proceed.
gcf:
addiu $sp,$sp,-4 # adjust the stack for an item
sw $ra,0($sp) # save return address
rem $t4,$a0,$a1 # r = a % b
beq $t4,$zero,L1 # if(r==0) go to L1
add $a0,$zero,$a1 # a = b
add $a1,$zero,$t4 # b = r
jr gcf
L1:
add $v0,$zero,$a1 # return b
addiu $sp,$sp,4 # pop 2 items
jr $ra # return to caller
There is absolutely nothing new to show here, the algorithm you just implemented is the Euclidean algorithm and it is well known in the literature1.
I will nonetheless write an informal analysis here as link only questions are evil.
First lets rewrite the code in an high level formulation:
unsigned int gcd(unsigned int a, unsigned int b)
{
if (a % b == 0)
return b;
return gcd(b, a % b);
}
The choice of unsigned int vs int was dicated by the MIPS ISA that makes rem undefined for negative operands.
Out goal is to find a function T(a, b) that gives the number of step the algorithm requires to compute the GDC of a and b.
Since a direct approach leads to nothing, we try by inverting the problem.
What pairs (a, b) makes T(a, b) = 1, in other words what pairs make gcd(a, b) terminates in one step?
We clearly must have that a % b = 0, which means that a must be a multiple of b.
There are actually an (countable) infinite number of pairs, we can limit our selves to pairs with the smallest, a and b2.
To recap, to have T(a, b) = 1 we need a = nb and we pick the pair (a, b) = (1, 1).
Now, given a pair (c, d) that requires N steps, how do we find a new pair (a, b) such that T(a, b) = T(c, d) + 1?
Since gcd(a, b) must take one step further then gcd(c, d) and since starting from gcd(a, b) the next step is gcd(b, a % b) we must have:
c = b => b = c
d = a % b => d = a % c => a = c + d
The step d = a % c => a = c + d comes from the minimality of a, we need the smallest a that when divided by c gives d, so we can take a = c + d since (c + d) % c = c % c d % c = 0 + d = d.
For d % c = d to be true we need that d < c.
Our base pair was (1, 1) which doesn't satisfy this hypothesis, luckily we can take (2, 1) as the base pair (convince your self that T(2, 1) = 1).
Then we have:
gcd(3, 2) = gcd(2, 1) = 1
T(3, 2) = 1 + T(2, 1) = 1 + 1 = 2
gcd(5, 3) = gcd(3, 2) = 1
T(5, 3) = 1 + T(3, 2) = 1 + 2 = 3
gcd(8, 5) = gcd(5, 3) = 1
T(8, 5) = 1 + T(5, 3) = 1 + 3 = 4
...
If we look at the pair (2, 1), (3, 2), (5, 3), (8, 5), ... we see that the n-th pair (starting from 1) is made by the number (Fn+1, Fn).
Where Fn is the n-th Fibonacci number.
We than have:
T(Fn+1, Fn) = n
Regarding Fibonacci number we know that Fn ∝ φn.
We are now going to use all the trickery of asymptotic analysis, particularly in the limit of the big-O notation considering φn or φn + 1 is the same.
Also we won't use the big-O symbol explicitly, we rather assume that each equality is true in the limit. This is an abuse, but makes the analysis more compact.
We can assume without loss of generality that N is an upper bound for both number in the pair and that it is proportional to φn.
We have N ∝ φn that gives logφ N = n, this ca be rewritten as log(N)/log(φ) = n (where logs are in base 10 and log(φ) can be taken to be 1/5).
Thus we finally have 5logN = n or written in reverse order
n = 5 logN
Where n is the number of step taken by gcd(a, b) where 0 < b < a < N.
We can further show that if a = ng and b = mg with n, m coprimes, than T(a, b) = T(n, m) thus the restriction of taking the minimal pairs is not bounding.
1 In the eventuality that you rediscovered such algorithm, I strongly advice against continue with reading this answer. You surely have a sharp mind that would benefit the most from a challenge than from an answer.
2 We'll later see that this won't give rise to a loss of generality.
This is what I tried to convert Octal number to binary.
What I wanted to do was to find the remainder of the given octal number when divided by 10 to get each digit and convert that digit to 3 bit binary. But this code is not producing any output. Please help on this.
Thanks in advance.
convert_bin(0, '0').
convert_bin(1, '1').
convert_bin(N, B) :-
N > 1,
X is N mod 2,
Y is N // 2,
convert_bin(Y, B1),
atom_concat(B1, X, B).
convert_oct(N, O) :-
X is N mod 10,
convert_bin(X, B),
Y is N // 10,
convert_oct(Y, O1),
atom_concat(O1, B, O).
The encoded number should better be a list of digits—not an atom!
Using clpfd and n_base_digits/3 we can write the following sample queries:
?- use_module(library(clpfd)).
true.
?- n_base_digits(27, 2, Binary).
Binary = [1,1,0,1,1].
?- n_base_digits(N, 2, [1,1,0,0,1,0,0,1]).
N = 201
; false.
?- n_base_digits(N, 2, [1,1,0,0,1,0,0,1]),
n_base_digits(N, 8, Octal).
N = 201, Octal = [3,1,1]
; false.
I'm new to Haskell, started learning a couple of days ago and I have a question on a function I'm trying to make.
I want to make a function that verifies if x is a factor of n (ex: 375 has these factors: 1, 3, 5, 15, 25, 75, 125 and 375), then removes the 1 and then the number itself and finally verifies if the number of odd numbers in that list is equal to the number of even numbers!
I thought of making a functions like so to calculate the first part:
factor n = [x | x <- [1..n], n `mod`x == 0]
But if I put this on the prompt it will say Not in scope 'n'. The idea was to input a number like 375 so it would calculate the list. What I'm I doing wrong? I've seen functions being put in the prompt like this, in books.
Then to take the elements I spoke of I was thinking of doing tail and then init to the list. You think it's a good idea?
And finally I thought of making an if statement to verify the last part. For example, in Java, we'd make something like:
(x % 2 == 0)? even++ : odd++; // (I'm a beginner to Java as well)
and then if even = odd then it would say that all conditions were verified (we had a quantity of even numbers equal to the odd numbers)
But in Haskell, as variables are immutable, how would I do the something++ thing?
Thanks for any help you can give :)
This small function does everything that you are trying to achieve:
f n = length evenFactors == length oddFactors
where evenFactors = [x | x <- [2, 4..(n-1)], n `mod` x == 0]
oddFactors = [x | x <- [3, 5..(n-1)], n `mod` x == 0]
If the "command line" is ghci, then you need to
let factor n = [x | x <- [2..(n-1)], n `mod` x == 0]
In this particular case you don't need to range [1..n] only to drop 1 and n - range from 2 to (n-1) instead.
The you can simply use partition to split the list of divisors using a boolean predicate:
import Data.List
partition odd $ factor 10
In order to learn how to write a function like partition, study recursion.
For example:
partition p = foldr f ([],[]) where
f x ~(ys,ns) | p x = (x:ys,ns)
f x ~(ys,ns) = (ys, x:ns)
(Here we need to pattern-match the tuples lazily using "~", to ensure the pattern is not evaluated before the tuple on the right is constructed).
Simple counting can be achieved even simpler:
let y = factor 375
(length $ filter odd y) == (length y - (length $ filter odd y))
Create a file source.hs, then from ghci command line call :l source to load the functions defined in source.hs.
To solve your problem this may be a solution following your steps:
-- computers the factors of n, gets the tail (strips 1)
-- the filter functions removes n from the list
factor n = filter (/= n) (tail [x | x <- [1..n], n `mod` x == 0])
-- checks if the number of odd and even factors is equal
oe n = let factors = factor n in
length (filter odd factors) == length (filter even factors)
Calling oe 10 returns True, oe 15 returns False
(x % 2 == 0)? even++ : odd++;
We have at Data.List a partition :: (a -> Bool) -> [a] -> ([a], [a]) function
So we can divide odds like
> let (odds,evens) = partition odd [1..]
> take 10 odds
[1,3,5,7,9,11,13,15,17,19]
> take 10 evens
[2,4,6,8,10,12,14,16,18,20]
Here is a minimal fix for your factor attempt using comprehensions:
factor nn = [x | n <- [1..nn], x <- [1..n], n `mod`x == 0]