dafny infinite set axioms and proving gcd lemma - infinite

Here is the goal. I am hoping to prove that given two numbers a and b, which are relatively prime I can show that there is some x and y such 1 = a*x+b*y. I copied implementation of GCD from KRML 279
lemma GcdLinearCombination(a: pos, b: pos)
ensures exists x,y :: Gcd(a,b) == a*x+b*y
{
Looking at the standard proof of this fact in text books, the proof makes use of an infinite set, asserting that some smallest d in this set is a linear combination of a and b and it also is the gcd. It involves diving a by d and showing that the remainder r is also of the same form, a linear combination of a and b, but because d is the smallest combination of that form is is a contradiction so r must be 0. Can we really construct a proof like this in Dafny?
function combinationSet(a: pos, b: pos): set<pos>
{
set x: nat,y: nat | 0 <= x <= a && 0 <= y <= b && a*x+b*y > 0 :: a*x+b*y
}
function icombinationSet(a: pos, b: pos): iset<pos>
{
iset x: nat,y: nat | a*x+b*y > 0 :: a*x+b*y
}
They then call upon the well-ordering principle to assert that some smallest d exists in this infinite set after demonstrating that it is not empty. Do I need to create an axiom that in a set of only positive numbers that such a number exists or is there another mechanism I can call upon to deduce this?
Trying to implement Min for an infinite set fails because the iset is not decreasing.
function iMin(s: iset<pos>): pos
requires s != iset{}
ensures forall x | x in s :: iMin(s) in s && iMin(s) <= x
{
var x :| x in s;
if s == iset{x} then
x
else
var y := iMin(s - iset{x}); //infinite set size is not decreasing as expected
assert forall z | z in s :: z == x || (z in (s - iset{x}) && y <= z);
if x < y then x else y
}

I have used nat instead of pos, but should be easy to port to pos.
lemma MinExist(s: set<nat>)
requires s != {}
ensures exists x :: x in s && forall y :: y in s ==> x <= y
{
var x := FindMin(s);
}
function FindMin(s: set<nat>): (min: nat)
requires s != {}
ensures min in s && forall y :: y in s ==> min <= y
{
var x :| x in s;
if s == {x} then
x
else
var s' := s - {x};
assert s == s' + {x};
var y := FindMin(s');
if x < y then x else y
}
function ISetMin(s: iset<nat>): nat
requires s != iset{}
{
ISetMinExists(s);
var x :| x in s && forall y :: y in s ==> x <= y;
x
}
lemma ISetMinExists (s: iset<nat>)
requires s != iset{}
ensures exists x :: x in s && forall y :: y in s ==> x <= y
{
var x :| x in s;
var rs := s - iset{x};
if rs == iset{}
{
forall i | i in s ensures x <= i {
if i == x {}
else {
assert s == iset{x};
assert i in iset{x};
assert false;
}
}
}
else {
var ss := set y | y < x ;
var tt := set y | y in ss && y in s;
if |tt| == 0 {
forall i | i in s ensures x <= i {
if i < x {
assert forall z :: z < x ==> z in ss;
assert i in ss;
assert i in tt;
}
}
}
else {
var y := FindMin(tt);
forall i | i in s ensures y <= i {
if i < x {
assert i in tt;
}
}
}
}
}

I did not finish, but here is a proof sketch. Note that I strengthened the postcondition of iMin and there are a few assumes that would need to be proven. Hope this helps !
lemma WellOrderingPrinciple(s: iset<nat>)
requires s != iset{}
ensures exists min :: min in s && forall x | x in s && x != min :: min < x;
function iMin(s: iset<nat>): nat
requires s != iset{}
// Change of the postcondition to be stronger
ensures iMin(s) in s && forall x | x in s && x != iMin(s) :: iMin(s) < x
{
WellOrderingPrinciple(s);
var min :| min in s && forall x | x in s && x != min :: min < x;
min
}
predicate IsGCD(a: nat, b: nat, g: nat) {
g > 0 && (a % g) == 0 && (b % g) == 0 &&
(forall x: nat | x > 0 && a % x == 0 && b % x == 0 ::
x <= g
)
}
function euclidianDivision(a: nat, d: nat): (result: (nat, nat))
requires d > 0
ensures result.0 == (a - (a % d))/d
ensures result.1 == a % d
ensures
calc {
result.0 * d + result.1;
{ assert result.0 == (a - (a % d))/d; }
((a - (a % d))/d)*d + result.1;
((a - (a % d))/d)*d + (a % d);
{ assume (a - (a % d)) % d == 0; } // TODO: Prove this
a - (a % d) + (a % d);
a;
}
result.0 * d + result.1 == a && 0 <= result.1 < d
{
((a - (a % d))/d, a % d)
}
lemma GcdLinearCombination(a: nat, b: nat, g: nat)
requires IsGCD(a, b, g)
requires a > 0 && b > 0
ensures exists x,y :: g == a*x+b*y
{
var allCombinations :=
iset x: int, y: int | a*x+b*y > 0 :: var j: nat := a*x+b*y; j;
assert allCombinations != iset{} by {
var x := 1;
var y := 1;
assert a*x+b*y > 0;
var j: nat := a*x+b*y;
assert j in allCombinations;
}
var d := iMin(allCombinations);
// Definition of d. Place where you need.
//assert d in allCombinations && (forall x <- allCombinations | x != d :: d < x);
assert d == g by {
assert exists x: int, y: int :: a*x+b*y == d;
var x, y :| a*x+b*y == d;
assert forall x | x in allCombinations && x != d :: d in allCombinations ==> d < x;
assert d > 0;
if a % d != 0 {
var (q, r) := euclidianDivision(a, d);
assert r != 0;
assert q * d + r == a;
var x' := 1-q*x;
var y': int := 0 - q*y;
calc <==> {
a == q * d + r;
a == q * (a*x + b*y) + r;
a - q * (a*x + b*y) == r;
r == a - q * (a*x + b*y);
r == a - q*(a*x) - q*(b*y);
r == a - q*(x*a) - q*(y*b);
r == a - (q*x)*a - (q*y)*b;
r == (1 - (q*x))*a - (q*y)*b;
r == x' * a + y' * b;
r == a* x' + b * y';
}
var j: nat := a* x' + b * y';
assert j in allCombinations;
assert j == r;
assert false;
}
if b % d != 0 {
var (q, r) := euclidianDivision(b, d);
assert r != 0;
assert q * d + r == b;
var y' := 1-q*y;
var x': int := 0 - q*x;
calc <==> {
b == q * d + r;
b == q * (a*x + b*y) + r;
b == q * (b*y + a*x) + r;
b - q * (b*y + a*x) == r;
r == b - q * (b*y + a*x);
r == b - q*(b*y) - q*(a*x);
r == b - q*(b*y) - q*(a*x);
r == b - (q*y)*b - (q*x)*a;
r == (1 - (q*y))*b - (q*x)*a;
r == y' * b + x' * a;
r == b* y' + a * x';
r == a * x' + b * y';
}
var j: nat := a* x' + b * y';
assert j in allCombinations;
assert j == r;
assert false;
}
// Ok, so now we proved that d divides a and d divides b
assert (a % d) == 0 && (b % d) == 0;
var (x', r0) := euclidianDivision(a, d);
var (y', r1) := euclidianDivision(b, d);
assert x' * d == a;
assert y' * d == b;
// Now, is it the biggest?
assert (forall x: nat | x > 0 && a % x == 0 && b % x == 0 :: x <= d) by {
forall x: nat | x > 0 && a % x == 0 && b % x == 0
ensures x <= d
{
assume false; // TODO
}
}
}
assert g in allCombinations;
}

The following seems to work for the infinite sets.
lemma WellOrderingPrinciple(s: iset<pos>)
requires s != iset{}
ensures exists min :: min in s && forall x | x in s && x != min :: min < x;
function iMin(s: iset<pos>): pos
requires s != iset{}
ensures forall x | x in s && x != iMin(s) :: iMin(s) in s ==> iMin(s) < x
{
WellOrderingPrinciple(s);
var min :| min in s && forall x | x in s && x != min :: min < x;
min
}

Related

What does the variable D do inside the while in this Bresenham's line drawing algorithm?

I've found this Generalized Bresenham's Line Drawing Algorithm and I'm having a hard time understanding what the while is doing here.
Any help is greatly appreciated.
the code:
#define sign(x) ((x > 0)? 1 : ((x < 0)? -1: 0))
x = x1;
y = y1;
dx = abs(x2 - x1);
dy = abs(y2 - y1);
s1 = sign(x2 - x1);
s2 = sign(y2 - y1);
swap = 0;
if (dy > dx) {
temp = dx;
dx = dy;
dy = temp;
swap = 1;
}
D = 2*dy - dx;
for (i = 0; i < dx; i++) {
display_pixel (x, y);
while (D >= 0) {
D = D - 2*dx;
if (swap)
x += s1;
else
y += s2;
}
D = D + 2*dy;
if (swap)
y += s2;
else
x += s1;
}
D is the scaled distance from the line to the candidate x, y coordinate.
Better: D is scaled difference of the distance from the line to the candidates x+1, y+0 and x+1, y+1.
That is, as x increments, the sign of D indicates should the closer y increment by 0 or 1?
(The role of x, y interchanges depending on which octant the algorithm is applied.)
I expected while (D >= 0) { as if (D >= 0) {. Bresenham's line algorithm
Note that OP's code is subject to overflow in abs(x2 - x1) and 2*dy - dx. Alternates exist that do not rely on wider math.

anyone have a better solution or method

I want to count if is the number of the row on the left group to make the configuration acceptable by the procedures. Output -1 if there is no acceptable configuration. the procedures is left a(X) middle b(x+1) and right c(x+2). does anyone have a better solution than mine?
#include<stdio.h>
int main(void)
{
int chairs,a,b,c,result;
scanf("%d %d %d %d", &chairs,&a ,&b , &c);
for(int i=1; i<=chairs; i++)
{
result= (a*(i)) + (b*(i+1)) + (c*(i+2));
if(chairs == result)
{
printf("%d", i);
break;
}
else if(i == chairs && chairs != result)
printf("-1");
}
}
This is rather a math problem.
a * x + b * (x + 1) + c * (x + 2) = chair
a * x + b * x + b + c * x + 2 * c = chair
a * x + b * x + c * x = chair - b - 2 * c
x * (a + b + c) = chair - b - 2 * c
x = (chair - b - 2 * c) / (a + b + c)
This can be solved in 1 operation. No solution if a + b + c == 0
It boils down to a math question
where
if ( (a+b+c) == 0) return -1 ;
X = (Chairs - b - 2c) / (a+b+c) , Y = (Chairs - b - 2c) % (a+b+c)
if X > 0 && X <= Chairs && y == 0
return X ;
else
return -1 ;

(Dafny) Adding elements of an array into another - loop invariant

I have a function sum that takes two arrays a and b as inputs and modifies b such that b[i] = a[0] + a[1] + ... + a[i]. I wrote this function and want to verify it with Dafny. However, Dafny tells me that my loop invariant might not be maintainted by the loop. Here is the code :
function sumTo(a:array<int>, n:int) : int
requires a != null;
requires 0 <= n < a.Length;
decreases n;
reads a;
{
if (n == 0) then a[0] else sumTo(a, n-1) + a[n]
}
method sum(a:array<int>, b:array<int>)
requires a != null && b != null
requires a.Length >= 1
requires a.Length == b.Length
modifies b
ensures forall x | 0 <= x < b.Length :: b[x] == sumTo(a,x)
{
b[0] := a[0];
var i := 1;
while i < b.Length
invariant b[0] == sumTo(a,0)
invariant 1 <= i <= b.Length
//ERROR : invariant might not be maintained by the loop.
invariant forall x | 1 <= x < i :: b[x] == sumTo(a,x)
decreases b.Length - i
{
b[i] := a[i] + b[i-1];
i := i + 1;
}
}
How can I fix this error?
Your program would not be correct if a and b reference the same array. You need the precondition a != b. (If you add it, Dafny will verify your program.)
Rustan

Error in C program to find integer triplets (x,y,z) such that n^x + n^y = n^z for given range of n

I want to make a C program compatible for DEV-C++ 4.9.9.2 to find integer triplets (x,y,z) such that for any integer n the equation n^x + n^y = n^z holds where n is any integer in the range [a,b]. The c program would have an input of only a and b and find such possible triplets.
The code that I wrote isn't working. What's the error in it?
for (n = a ; n <= b ; n++) {
for (x = a ; x < b ; x++) {
for (y = a ; y < b ; y++) {
for (z = a ; z = b ; z++) {
c = pow(n, x);
d = pow(n, y);
e = pow(n, z);
f = c + d;
if (e = f) {
printf("(%d , %d , %d) : %d", x,y,z,n);
}
}
}
}
}
I'm a novice in C.
C correction
Try changing
if (e=f)
into
if (e==f)
The first does assignment, the second tests equality.
(Note that you may also get overflow if the numbers tested get larger than your datatype.)
Maths approach
If y==x, then:
n^x + n^x = n^z
2n^x = n^z
=> n == 0 or n == 2
Now, assume y>x and n!=0.
n^x + n^y = n^z
n^x ( 1 + n^(y-x)) = n^z
=> 1+n^(y-x) = n^(z-x)
=> 1 = 0 ( modulo n)
=> impossible unless n==0 (in which case any x,y works) or n==1 (which does not work)
So this equation has solutions for any x,y if n==0.
Otherwise, the only solutions are with n==2, x==y and z=x+1.
Change
if (e = f)
to
if (e == f)
The first one assigns f to e, enable compiler warnings for such mistakes. The second one equates the LHS to the RHS.
Secondly, assuming your program is a brute force, i.e., loops for all values of x, y and z, you might want to change this statement:
for (z = a ; z = b ; z++)
to
for (z = a ; z < b ; z++)
Your implementation is O(n^4) , actually it can be done in O(n^3) .Here is the code
for (n = a ; n <= b ; n++) {
for (x = a ; x < b ; x++) {
for (y = a ; y < b ; y++) {
{
c = pow(n, x);
d = pow(n, y);
f = c + d;
e = pow(f,1.0/n);
if (e >= a && e < b) {
z = e;
printf("(%d , %d , %d) : %d", x,y,z,n);
}
}
}
}
}

Recursion to Iteration - Scheme to C

Can somewone help me convert this scheme function:
#lang racket
(define (powmod2 x e m)
(define xsqrm (remainder (* x x) m))
(cond [(= e 0) 1]
[(even? e) (powmod2 xsqrm (/ e 2) m)]
[(odd? e) (remainder (* x (powmod2 xsqrm (/ (sub1 e) 2) m)) m)]))
Into a function in C, and don't use recursion i.e use iteration.
I'm out of ideas', the part that is bothering me is when e is odd and then the recursive call is in the remainder function. I dont know how to transfer that in a while loop? any tips or suggestions:
This is what i have so far:
int powmod2(int x, int e, int m) {
int i = x;
int xsqrm = ((x * x) % m);
while (e != 0){
if (e%2 == 0) {
x = xsqrm;
e = (e/2);
xsqrm = ((x * x) % m);
}
else {
i = x;
x = xsqrm;
e = (e - 1)/2;
xsqrm = ((x * x) % m);
}
}
e = 1;
return (i*e)%m;
}
The even version is straightforward because the code has been written tail recursively so the call to (powmod2 xsqrm (/ e 2) m) can be expressed iteratively by replacing e with half of e and x with its square modulo m:
int powmod2(int x, int e, int m) { /* version for when e is a power of 2 */
while ((e /= 2) != 0)
x = (x * x) % m;
return x;
}
However the odd version has not been written tail recursively. One approach is to create a helper method that uses an accumulator. This helper method can then be written tail recursively for both even and odd exponent. You can then transform that into an iteration.
You are having trouble doing the conversion because the original scheme code is not tail recursive. Try to add extra parameters to powmod2 so that you do not need to do the multiplication by remainder in the odd case after calling the recursive function.
To illustrate, its hard to loopify the following function
int fac(n){
if(n == 0) {
return 1;
}else{
return n * fac(n-1)
}
}
But it is easy to loopify the version with an accumulation parameter
int fac(n, res){
if(n == 0) {
return res;
}else{
return fac(n-1, res*n)
}
}
int real_fac(n){ return fac(n, 1); }
Perhaps if you were to run the algorithm with some values to see how the result is calculated, it can help you figure out how to convert it. Let's see a single run for x=5, e=5 and m=7:
1. x=5, e=5, m=7
xsqrm=4
e:odd => res = 5*...%7
2. x=4, e=2, m=7
xsqrm=2
e:even => res = ...%7
3. x=2, e=1, m=7
xsqrm=4
e:odd => res = 2*...%7
4. x=4, e=0, m=7
e==0 => res = 1
res = 5*2%7=3
At step 1, we get a partial calculation for the result: it is 5 times the result of next step mod 7. At step 2, since it is even the result is the same as the result of the next step. At step 3, we've got something similar to step 1. The result we'll feed upstairs is calculated by multiplying next result by 2 (mod 7 again). And at termination, we've got our result to feed upstairs: 1. Now, as we go up, we just know how to calculate res: 2*1%7 for step 3, 2 for step 2, and 2*5%7 for step 1.
One way to implement it is to use a stack. At every partial result, if the exponent is odd, we can push the multiplication factor to the stack, and once we terminate, we can just multiply them all. This is the naive/cheating method for conversion.
There is a more efficient way that you should be able to see when you look at the steps above. Also other answers about converting everything to tail recursive is a very good hint.
The easiest way is to reason what is the original function trying to compute? This is the value of x to the power e module m. If you express e in binary, you can get e = e0 * 1 + e1 * 2 + e2 * 4 + e3 * 8 + ..., where en is either 0 or 1. And x^n = x * e0 + x ^ 2 * e1 + x ^ 4 * e2 + x ^ 8 * e3 + ....
By using the mathematical properties of the modulo operator, ie. (a + b) % m = ((a % m) + (b % m)) % m and (a * b) % m = ((a % m) * (b % m)) % m, we can then rewrite the function as:
int powmod2(int x, int e, int m) {
// This correspond to (= e 0)
int r = 1;
while (e != 0) {
if (e % 2) {
// This correspond to (odd? e)
r = (r * x) % m;
}
// This correspond to the recursive call
// that is done whatever the parity of e.
x = (x * x) % m;
e /= 2;
}
return r;
}
The first step would be writing the original Scheme procedure as a tail recursion. Notice that this rewrite works because of the properties of modular arithmetic:
(define (powmod2 x e m)
(define (iter x e acc)
(let ((xsqrm (remainder (* x x) m)))
(cond ((zero? e) acc)
((even? e) (iter xsqrm (/ e 2) acc))
(else (iter xsqrm (/ (sub1 e) 2) (remainder (* x acc) m))))))
(iter x e 1))
The key element of the above procedure is that the answer is passed in the acc parameter. Now we have a tail recursion, after that the conversion to a fully iterative solution is pretty straightforward:
int powmod2(int x, int e, int m) {
int acc = 1;
int xsqrm = 0;
while (e != 0) {
xsqrm = (x * x) % m;
if (e % 2 == 0) {
x = xsqrm;
e = e / 2;
}
else {
acc = (x * acc) % m;
x = xsqrm;
e = (e - 1) / 2;
}
}
return acc;
}
It can be optimized further, like this:
int powmod2(int x, int e, int m) {
int acc = 1;
while (e) {
if (e & 1) {
e--;
acc = (x * acc) % m;
}
x = (x * x) % m;
e >>= 1;
}
return acc;
}

Resources