changeset 1626:89384d54d49a draft

Teach factor to accept whitespace separated arguments (reported by Robert Thompson). (The diff looks bigger than it is because of reindenting.)
author Rob Landley <rob@landley.net>
date Wed, 24 Dec 2014 16:13:08 -0600
parents 1cc305c51cde
children 6c80a3b4e634
files tests/factor.test toys/other/factor.c
diffstat 2 files changed, 42 insertions(+), 33 deletions(-) [+]
line wrap: on
line diff
--- a/tests/factor.test	Tue Dec 23 19:20:24 2014 -0600
+++ b/tests/factor.test	Wed Dec 24 16:13:08 2014 -0600
@@ -16,3 +16,7 @@
         "10000000018: 2 131 521 73259\n" "" ""
 testing "factor 10000000019" "factor 10000000019" \
         "10000000019: 10000000019\n" "" ""
+
+testing "factor 3 6 from stdin" "factor" "3: 3\n6: 2 3\n" "" "3 6"
+testing "factor stdin newline" "factor" "3: 3\n6: 2 3\n" "" "3\n6\n"
+
--- a/toys/other/factor.c	Tue Dec 23 19:20:24 2014 -0600
+++ b/toys/other/factor.c	Wed Dec 24 16:13:08 2014 -0600
@@ -21,46 +21,51 @@
 {
   long l, ll;
 
-  l = strtol(s, &s, 0);
-  if (*s) {
-    error_msg("%s: not integer");
-    return;
-  }
-
-  printf("%ld:", l);
+  for (;;) {
+    while(isspace(*s)) s++;
+    if (!*s) return;
 
-  // Negative numbers have -1 as a factor
-  if (l < 0) {
-    printf(" -1");
-    l *= -1;
-  }
+    l = strtol(s, &s, 0);
+    if (*s && !isspace(*s)) {
+      error_msg("%s: not integer");
+      return;
+    }
 
-  // Deal with 0 and 1 (and 2 since we're here)
-  if (l < 3) {
-    printf(" %ld\n", l);
-    return;
-  }
+    printf("%ld:", l);
+
+    // Negative numbers have -1 as a factor
+    if (l < 0) {
+      printf(" -1");
+      l *= -1;
+    }
 
-  // Special case factors of 2
-  while (l && !(l&1)) {
-    printf(" 2");
-    l >>= 1;
-  }
+    // Nothing below 4 has factors
+    if (l < 4) {
+      printf(" %ld\n", l);
+      continue;
+    }
 
-  // test odd numbers.
-  for (ll=3; ;ll += 2) {
-    long lll = ll*ll;
+    // Special case factors of 2
+    while (l && !(l&1)) {
+      printf(" 2");
+      l >>= 1;
+    }
 
-    if (lll>l || lll<ll) {
-      if (l>1) printf(" %ld", l);
-      break;
+    // test odd numbers.
+    for (ll=3; ;ll += 2) {
+      long lll = ll*ll;
+
+      if (lll>l || lll<ll) {
+        if (l>1) printf(" %ld", l);
+        break;
+      }
+      while (!(l%ll)) {
+        printf(" %ld", ll);
+        l /= ll;
+      }
     }
-    while (!(l%ll)) {
-      printf(" %ld", ll);
-      l /= ll;
-    }
+    xputc('\n');
   }
-  xputc('\n');
 }
 
 void factor_main(void)