Use '->' in prolog - if-statement

I want to generate a list that is made up by sublists which contains 2 intergers and their sum and product.
The expected result is
A = [[2,3,5,6],[2,4,6,8],[2,5,7,10],[2,6,8,12],
[2,7,9,14],[2,8,10,16],[3,4,7,12],[3,5,8,15],
[3,6,9,18],[3,7,10,21],[4,5,9,20]].
But I kept have some sublists that does not have the sum and product:
?- get(A).
A = [[2,3,5,6],[2,4,6,8],[2,5,7,10],[2,6,8,12],
[2,7,9,14],[2,8,10,16],[2,_G419,_G422,_G425],
[3,4,7,12],[3,5,8,15],[3,6,9,18],[3,7,10,21],
[3,_G530,_G533,_G536],[4,5,9,20]].
Here is my code :
get(4,5,[]):-!.
get(N,M,[[N,Q,S,P]|List]):-
Q is M + 1,
S is N + Q,
S =< 10 ->
P is N * Q,
get(N,Q,List);
X is N + 1,
get(X,X,List).
get(List):-get(2,2,List).
I think the problem is about using -> in my code, but I don't know how to fix it, I think the logic about -> is right: if S=<10, then calculate the product and the other value with N and Q; else calculate N+1 and N+2 and ...

The operator precedence of (->)/2 is higher than the
operator precedence of (,)/2. As a result the (,)/2
are grouped together as an argument for (->)/2.
So your rule:
get(N,M,[[N,Q,S,P]|List]):-
Q is M + 1,
S is N + Q,
S =< 10 ->
P is N * Q,
get(N,Q,List);
X is N + 1,
get(X,X,List).
Is basically read by the interpreter as:
get(N,M,[[N,Q,S,P]|List]):-
(Q is M + 1,
S is N + Q,
S =< 10) ->
P is N * Q,
get(N,Q,List);
X is N + 1,
get(X,X,List).
With the result that Q ans S are unbound when
the if condition is not satisfied and the else
part is executed. You can fix your code by introducing
additional parenthesis:
get(N,M,[[N,Q,S,P]|List]):-
Q is M + 1,
S is N + Q,
(S =< 10 ->
P is N * Q,
get(N,Q,List)
; X is N + 1,
get(X,X,List)).
But even with this fix, there is an issue with P
being unbound in the else branch.
For clarity, you might even try a solution without
if-then-else, see for example here
Prolog removing IF THEN ELSE

I concur with Jan, but I want to inteject a point about formatting. Because ; and -> so strongly affect the meaning of a program, it's poor form (meaning makes it harder to understand) to put those operators at the end of a line.
get(N,M,[[N,Q,S,P]|List]):-
Q is M + 1,
S is N + Q,
S =< 10
->
P is N * Q,
get(N,Q,List)
; X is N + 1,
get(X,X,List).
When you arrange code like this it becomes immediately apparent that the entire clause is an if-then-else, with the first 3 lines being the 'if' portion. (Though I wouldn't object to Jan's layout for the final version.)

Related

Polynomial Long Division in OCaml

I'm trying to implement polynomial long division based on polynomials of type int array. Here the highest degree coefficients are at the end. I'm basing my code off of the pseudo code available on Wikipedia:
function n / d is
require d ≠ 0
q ← 0
r ← n // At each step n = d × q + r
while r ≠ 0 and degree(r) ≥ degree(d) do
t ← lead(r) / lead(d) // Divide the leading terms
q ← q + t
r ← r − t × d
return (q, r)
H
This line
q = poly_add q t
is testing for the equality between q and poly_add q t, it is not an assignment and the compiler is warning you that you are ignoring the result of this test. You are also misunderstanding your pseudo-code: t is supposed to be a polynomial of degree degree r - degree d.
You need to use references, or transform your while loop into a recursive function.
Similarly, since r is an array, whose length cannot be changed:
while ((Array.length r) >= n2) && (Array.length r != 0)do
This test does not change during the loop. Structural inequality is <>.
Another issue is that this line
t.(0) <- r.((Array.length r)-1)/p2.(n2-1)
is mutating your zero polynomial which is a bad idea.
Overall, it is not clear if your polynomial are supposed to be mutable or not.
If they are not supposed to be mutable, you should avoid a.( ) <- altogether.

How to prove that a number is prime using Znumtheory in Coq

I'm trying to prove that a number is prime using the Znumtheory library.
In Znumtheory primes are defined in terms of relative primes:
Inductive prime (p:Z) : Prop :=
prime_intro :
1 < p -> (forall n:Z, 1 <= n < p -> rel_prime n p) -> prime p.
So to prove that 3 is prime I should apply prime_intro to the goal. Here is my try:
Theorem prime3 : prime 3.
Proof.
apply prime_intro.
- omega.
- intros.
unfold rel_prime. apply Zis_gcd_intro.
+ apply Z.divide_1_l.
+ apply Z.divide_1_l.
+ intros. Abort.
I don't know how to use the hypothesis H : 1 <= n < 3 which says that n is 1 or 2. I could destruct it, apply lt_eq_cases and destruct it again, but I would be stuck with a useless 1 < n in the first case.
I wasn't expecting to have a hard time with something that looks so simple.
I have a variant of #larsr's proof.
Require Import ZArith.
Require Import Znumtheory.
Require Import Omega.
Theorem prime3 : prime 3.
Proof.
constructor.
- omega.
- intros.
assert (n = 1 \/ n = 2) as Ha by omega.
destruct Ha; subst n; apply Zgcd_is_gcd.
Qed.
Like #larsr's proof, we prove that 1 < 3 using omega and then prove that either n=1 or n=2 using omega again.
To prove rel_prime 1 3 and rel_prime 2 3 which are defined in terms of Zis_gcd, we apply Zgcd_is_gcd. This lemma states that computing the gcd is enough. This is trivial on concrete inputs like (1,3) and (2,3).
EDIT: We can generalize this result, using only Gallina. We define a boolean function is_prime that we prove correct w.r.t. the inductive specification prime. I guess this can be done in a more elegant way, but I am confused with all the lemmas related to Z. Moreover, some of the definitions are opaque and cannot be used (at least directly) to define a computable function.
Require Import ZArith.
Require Import Znumtheory.
Require Import Omega.
Require Import Bool.
Require Import Recdef.
(** [for_all] checks that [f] is true for any integer between 1 and [n] *)
Function for_all (f:Z->bool) n {measure Z.to_nat n}:=
if n <=? 1 then true
else f (n-1) && for_all f (n-1).
Proof.
intros.
apply Z.leb_nle in teq.
apply Z2Nat.inj_lt. omega. omega. omega.
Defined.
Lemma for_all_spec : forall f n,
for_all f n = true -> forall k, 1 <= k < n -> f k = true.
Proof.
intros.
assert (0 <= n) by omega.
revert n H1 k H0 H.
apply (natlike_ind (fun n => forall k : Z, 1 <= k < n ->
for_all f n = true -> f k = true)); intros.
- omega.
- rewrite for_all_equation in H2.
destruct (Z.leb_spec0 (Z.succ x) 1).
+ omega.
+ replace (Z.succ x - 1) with x in H2 by omega. apply andb_true_iff in H2.
assert (k < x \/ k = x) by omega.
destruct H3.
* apply H0. omega. apply H2.
* subst k. apply H2.
Qed.
Definition is_prime (p:Z) :=
(1 <? p) && for_all (fun k => Z.gcd k p =? 1) p.
Theorem is_prime_correct : forall z, is_prime z = true -> prime z.
Proof.
intros. unfold is_prime in H.
apply andb_true_iff in H. destruct H as (H & H0).
constructor.
- apply Z.ltb_lt. assumption.
- intros.
apply for_all_spec with (k:=n) in H0; try assumption.
unfold rel_prime. apply Z.eqb_eq in H0. rewrite <- H0.
apply Zgcd_is_gcd.
Qed.
The proof becomes nearly as simple as #Arthur's one.
Theorem prime113 : prime 113.
Proof.
apply is_prime_correct; reflexivity.
Qed.
The lemma you mentioned is actually proved in that library, under the name prime_3. You can look up its proof on GitHub.
You mentioned how strange it is to have such a hard time to prove something so simple. Indeed, the proof in the standard library is quite complicated. Luckily, there are much better ways to work out this result. The Mathematical Components library advocates for a different style of development based on boolean properties. There, prime is not an inductively defined predicate, but a function nat -> bool that checks whether its argument is prime. Because of this, we can prove such simple facts by computation:
From mathcomp Require Import ssreflect ssrbool ssrnat prime.
Lemma prime_3 : prime 3. Proof. reflexivity. Qed.
There is a bit of magic going on here: the library declares a coercion is_true : bool -> Prop that is automatically inserted whenever a boolean is used in a place where a proposition is expected. It is defined as follows:
Definition is_true (b : bool) : Prop := b = true.
Thus, what prime_3 really is proving above is prime 3 = true, which is what makes that simple proof possible.
The library allows you to connect this boolean notion of what a prime number is to a more conventional one via a reflection lemma:
Lemma primeP p :
reflect (p > 1 /\ forall d, d %| p -> xpred2 1 p d) (prime p).
Unpacking notations and definitions, what this statement says is that prime p equals true if and only if p > 1 and every d that divides p is equal to 1 or p. I am afraid it would be a lengthy detour to explain how this reflection lemma works exactly, but if you find this interesting I strongly encourage you to look up more about Mathematical Components.
Here is a proof that I think is quite understandable as one steps through it.
It stays at the level of number theory and doesn't unfold definitions that much. I put in some comments, don't know if it makes it more or less readable. But try to step through it in the IDE, if you care for it...
Require Import ZArith.
Require Import Znumtheory.
Inductive prime (p:Z) : Prop :=
prime_intro :
1 < p -> (forall n:Z, 1 <= n < p -> rel_prime n p) -> prime p.
Require Import Omega.
Theorem prime3 : prime 3.
Proof.
constructor.
omega. (* prove 1 < 3 *)
intros; constructor. (* prove rel_prime n 3 *)
exists n. omega. (* prove (1 | n) *)
exists 3. omega. (* prove (1 | 3) *)
(* our goal is now (x | 1), and we know (x | n) and (x | 3) *)
assert (Hn: n=1 \/ n=2) by omega; clear H. (* because 1 <= n < 3 *)
case Hn. (* consider cases n=1 and n=2 *)
- intros; subst; trivial. (* case n = 1: proves (x | 1) because we know (x | n) *)
- intros; subst. (* case n = 2: we know (x | n) and (x | 3) *)
assert (Hgcd: (x | Z.gcd 2 3)) by (apply Z.gcd_greatest; trivial).
(* Z.gcd_greatest: (x | 2) -> x | 3) -> (x | Z.gcd 2 3) *)
apply Hgcd. (* prove (x | 1), because Z.gcd 2 3 = 1 *)
Qed.
Fun fact: #epoiner's answer can be used together with Ltac in a proof script for any prime number.
Theorem prime113 : prime 113.
Proof.
constructor.
- omega.
- intros n H;
repeat match goal with | H : 1 <= ?n < ?a |- _ =>
assert (Hn: n = a -1 \/ 1 <= n < a - 1) by omega;
clear H; destruct Hn as [Hn | H];
[subst n; apply Zgcd_is_gcd | simpl in H; try omega ]
end.
Qed.
However, the proof term gets unwieldy, and checking becomes slower and slower. This is why it small scale reflection (ssreflect) where computation is moved into the type checking probably is preferrable in the long run. It's hard to beat #Arthur Azevedo De Amorim's proof:
Proof. reflexivity. Qed. :-) Both in terms of computation time, and memory-wise.

Range Update - Range Query using Fenwick Tree

http://ayazdzulfikar.blogspot.in/2014/12/penggunaan-fenwick-tree-bit.html?showComment=1434865697025#c5391178275473818224
For example being told that the value of the function or f (i) of the index-i is an i ^ k, for k> = 0 and always stay on this matter. Given query like the following:
Add value array [i], for all a <= i <= b as v Determine the total
array [i] f (i), for each a <= i <= b (remember the previous function
values ​​clarification)
To work on this matter, can be formed into Query (x) = m * g (x) - c,
where g (x) is f (1) + f (2) + ... + f (x).
To accomplish this, we
need to know the values ​​of m and c. For that, we need 2 separate
BIT. Observations below for each update in the form of ab v. To
calculate the value of m, virtually identical to the Range Update -
Point Query. We can get the following observations for each value of
i, which may be:
i <a, m = 0
a <= i <= b, m = v
b <i, m = 0
By using the following observation, it is clear that the Range Update - Point Query can be used on any of the BIT. To calculate the value of c, we need to observe the possibility for each value of i, which may be:
i <a, then c = 0
a <= i <= b, then c = v * g (a - 1)
b <i, c = v * (g (b) - g (a - 1))
Again, we need Range Update - Point Query, but in a different BIT.
Oiya, for a little help, I wrote the value of g (x) for k <= 3 yes: p:
k = 0 -> x
k = 1 -> x * (x + 1) / 2
k = 2 -> x * (x + 1) * (2x + 1) / 6
k = 3 -> (x * (x + 1) / 2) ^ 2
Now, example problem SPOJ - Horrible Queries . This problem is
similar issues that have described, with k = 0. Note also that
sometimes there is a matter that is quite extreme, where the function
is not for one type of k, but it could be some that polynomial shape!
Eg LA - Alien Abduction Again . To work on this problem, the solution
is, for each rank we make its BIT counter m respectively. BIT combined
to clear the counters c it was fine.
How can we used this concept if:
Given an array of integers A1,A2,…AN.
Given x,y: Add 1×2 to Ax, add 2×3 to Ax+1, add 3×4 to Ax+2, add 4×5 to
Ax+3, and so on until Ay.
Then return Sum of the range [Ax,Ay].

Building a list of n length same value Prolog

I want to build/3 a list in Prolog of N elements, each element should be X.
?- build(30,3,L).
L = [30,30,30].
Spent a good few hours on it, keep ending up in either a infinite loop or the variables aren't instantiated properly.
build(_,0,[]).
build(X,N1,[X]):- N1>0, N1 is N - 1, build(X,N,[]).
build(X,N1,[X|L]) :- N1 > 0, N1 is N - 1, build(X,N,L).
Using meta-predicates makes it very short:
(1) with maplist/2: creates a list of length N and then matches all its elements to X.
build(X, N, List) :-
length(List, N),
maplist(=(X), List).
(2) with findall/3: makes loop N-times and completes List with X N-times
build(X, N, List) :-
findall(X, between(1, N, _), List).
build(_,0,[]). % any value, repeated 0 times, makes for an empty list
good.
build(X,N1,[X|L]) :- % a value X, repeated N1 times, makes for [X|L] list, _if_ ...
N1 > 0, N1 is N - 1, % N1 is positive, and L is
build(X,N,L). % one element shorter... right?
excellent. huh? N is N1 - 1 you mean.
build(X,N1,[X]):- N1>0, N1 is N - 1, build(X,N,[]).
why?? [X] is already matched by the previous rule, [X] = [X | [] ] = [X | L], and the empty list L = [] will be matched by the first rule.
You don't need this rule at all.

Properties of the modulo operation

I have the compute the sum S = (a*x + b*y + c) % N. Yes it looks like a quadratic equation but it is not because the x and y have some properties and have to be calculated using some recurrence relations. Because the sum exceeds even the limits of unsigned long long I want to know how could I compute that sum using the properties of the modulo operation, properties that allow the writing of the sum something like that(I say something because I do not remember exactly how are those properties): (a*x)%N + (b*y)%N + c%N, thus avoiding exceeding the limits of unsigned long long.
Thanks in advance for your concern! :)
a % N = x means that for some integers 0 <= x < N and m: m * N + x = a.
You can simply deduce then that if a % N = x and b % N = y then
(a + b) % N =
= (m * N + x + l * N + y) % N =
= ((m + l) * N + x + y) % N =
= (x + y) % N =
= (a % N + b % N) % N.
We know that 0 < x + y < 2N, that is why you need to keep remainder calculation. This shows that it is okay to split the summation and calculate the remainders separately and then add them, but don't forget to get the remainder for the sum.
For multiplication:
(a * b) % N =
= ((m * N + x) * (l * N + y)) % N =
= ((m * l + x * l + m * y) * N + x * y) % N =
= (x * y) % N =
= ((a % N) * (b % N)) % N.
Thus you can also do the same with products.
These properties can be simply derived in a more general setting using some abstract algebra (the remainders form a factor ring Z/nZ).
You can take the idea even further, if needed:
S = ( (a%N)*(x%N)+(b%N)*(y%N)+c%N )%N
You can apply the modulus to each term of the sum as you've suggested; but even so after summing them you must apply the modulus again to get your final result.
How about this:
int x = (7 + 7 + 7) % 10;
int y = (7 % 10 + 7 % 10 + 7 % 10) % 10;
You remember right. The equation you gave, where you %N every of the summands is correct. And that would be exactly what I use. You should also %N for every partial sum (and the total) again, as the addition results can be still greater than N. BUT be careful this works only if your size limit is at least twice as big as your N. If this is not the case, it can get really nasty.
Btw for the following %N operations of the partial sums, you dont have to perform a complete division, a check > N and if bigger just subtraction of N is enough.
Not only can you reduce all variable mod n before starting the calculation, you can write your own mod-mul to compute a*x mod n by using a shift-and-add method and reduce the result mod n at each step. That way your intermediate calculations will only require one more bit than n. Once these products are computed, you can add them pairwise and reduce mod n after each addition which will also not require more than 1 bit beyond the range of n.
There is a python implementation of modular multiplication in my answer to this question. Conversion to C should be trivial.