improve by only searching halfway
authorMart Lubbers <mart@martlubbers.net>
Tue, 7 Dec 2021 08:06:14 +0000 (09:06 +0100)
committerMart Lubbers <mart@martlubbers.net>
Tue, 7 Dec 2021 08:06:14 +0000 (09:06 +0100)
07b.c

diff --git a/07b.c b/07b.c
index 87ba2f0..a711578 100644 (file)
--- a/07b.c
+++ b/07b.c
@@ -24,17 +24,18 @@ int main()
                ncrabs++;
        }
 
-       int mindist = INT_MAX;
-       for (int i = minp; i<=maxp; i++) {
-               int dist = 0;
+       int lastdist = INT_MAX;
+       int dist = INT_MAX;
+       int i = minp;
+       do {
+               lastdist = dist;
+               dist = 0;
                for (int j = 0; j<ncrabs; j++) {
                        int d = abs(crabs[j]-i);
-                       for (int k = 1; k<=d; k++) {
+                       for (int k = 1; k<=d; k++)
                                dist += k;
-                       }
                }
-               if (dist < mindist)
-                       mindist = dist;
-       }
-       printf("%d\n", mindist);
+               i++;
+       } while (dist < lastdist);
+       printf("%d\n", lastdist);
 }