| 1 | /*
|
|---|
| 2 | Author: Yihao Yan
|
|---|
| 3 |
|
|---|
| 4 | See challenge 2 of: http://etaps2015.verifythis.org/challenges
|
|---|
| 5 |
|
|---|
| 6 | -----------------
|
|---|
| 7 | Problem description:
|
|---|
| 8 |
|
|---|
| 9 | Various parallel GCD algorithms exist. In this challenge, we consider a
|
|---|
| 10 | simple Euclid-like algorithm with two parallel threads. One thread
|
|---|
| 11 | subtracts in one direction, the other thread subtracts in the other
|
|---|
| 12 | direction, and eventually this procedure converges on GCD.
|
|---|
| 13 |
|
|---|
| 14 | Verification tasks
|
|---|
| 15 | ------------------
|
|---|
| 16 |
|
|---|
| 17 | Specify and verify the following behaviour of this parallel GCD algorithm:
|
|---|
| 18 |
|
|---|
| 19 | Input: two positive integers a and b
|
|---|
| 20 | Output: a positive number that is the greatest common divisor of a and b
|
|---|
| 21 |
|
|---|
| 22 | -----------------
|
|---|
| 23 | Result:
|
|---|
| 24 |
|
|---|
| 25 | For any numbers A less than 5 and B less than 7, myGCD returns a common divisor d
|
|---|
| 26 | of them and the verification shows that there exists no common divisor of A and
|
|---|
| 27 | B that is greater than d. Therefore, myGCD behaves correctly.
|
|---|
| 28 |
|
|---|
| 29 | -----------------
|
|---|
| 30 | command: civl verify parallelGCD.c
|
|---|
| 31 | */
|
|---|
| 32 |
|
|---|
| 33 | #include <civlc.cvh>
|
|---|
| 34 | #include <stdio.h>
|
|---|
| 35 |
|
|---|
| 36 | $input int A_BOUND=4;
|
|---|
| 37 | $input int B_BOUND=6;
|
|---|
| 38 | $input int A;
|
|---|
| 39 | $input int B;
|
|---|
| 40 | $assume (A>0 && B>0 && A<A_BOUND && B<B_BOUND);
|
|---|
| 41 |
|
|---|
| 42 | int myGCD(int a, int b) {
|
|---|
| 43 | $proc proc_a;
|
|---|
| 44 | $proc proc_b;
|
|---|
| 45 |
|
|---|
| 46 | void worker1() {
|
|---|
| 47 | while(a != b){
|
|---|
| 48 | if(a>b){
|
|---|
| 49 | int t1 = b;
|
|---|
| 50 | int t2 = a-t1;
|
|---|
| 51 | a = t2;
|
|---|
| 52 | }
|
|---|
| 53 | }
|
|---|
| 54 | }
|
|---|
| 55 | void worker2() {
|
|---|
| 56 | while(a != b) {
|
|---|
| 57 | if(b>a) {
|
|---|
| 58 | int t1 = a;
|
|---|
| 59 | int t2 = b-t1;
|
|---|
| 60 | b = t2;
|
|---|
| 61 | }
|
|---|
| 62 | }
|
|---|
| 63 | }
|
|---|
| 64 | proc_a= $spawn worker1();
|
|---|
| 65 | proc_b= $spawn worker2();
|
|---|
| 66 | $wait(proc_a);
|
|---|
| 67 | $wait(proc_b);
|
|---|
| 68 | return a;
|
|---|
| 69 | }
|
|---|
| 70 |
|
|---|
| 71 | int seqGCD(int a, int b) {
|
|---|
| 72 | while(a != b) {
|
|---|
| 73 | if(a > b)
|
|---|
| 74 | a = a-b;
|
|---|
| 75 | if(b > a)
|
|---|
| 76 | b = b-a;
|
|---|
| 77 | }
|
|---|
| 78 | return a;
|
|---|
| 79 | }
|
|---|
| 80 |
|
|---|
| 81 | void main() {
|
|---|
| 82 | int result1 = myGCD(A, B);
|
|---|
| 83 | int minAB = A < B ? A : B;
|
|---|
| 84 |
|
|---|
| 85 | $assert($forall (int i: (result1+1) .. (minAB)) (A%i != 0 || B%i != 0));
|
|---|
| 86 | $assert(A%result1 == 0 && B%result1 == 0);
|
|---|
| 87 | }
|
|---|