coreutils
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[PATCH 1/2] factor: add option for printing in x^y format


From: Rasmus Villemoes
Subject: [PATCH 1/2] factor: add option for printing in x^y format
Date: Wed, 27 Apr 2022 12:07:20 +0200

When factoring numbers that have a large 2^n factor, it can be hard to
eyeball just how many 2's there are. Add an option to print each prime
power factor in the x^y format (omitting the exponent when it is 1).

* src/factor.c: Add --exponents option for printing in x^y format.

Signed-off-by: Rasmus Villemoes <rasmus.villemoes@prevas.dk>
---
 src/factor.c | 25 ++++++++++++++++++++++++-
 1 file changed, 24 insertions(+), 1 deletion(-)

diff --git a/src/factor.c b/src/factor.c
index 66ce28b84..9095b6973 100644
--- a/src/factor.c
+++ b/src/factor.c
@@ -226,12 +226,16 @@ enum
 
 static struct option const long_options[] =
 {
+  {"exponents", no_argument, NULL, 'e'},
   {"-debug", no_argument, NULL, DEV_DEBUG_OPTION},
   {GETOPT_HELP_OPTION_DECL},
   {GETOPT_VERSION_OPTION_DECL},
   {NULL, 0, NULL, 0}
 };
 
+/* If true, use x^y output format.  */
+static bool print_exponents;
+
 struct factors
 {
   uintmax_t     plarge[2]; /* Can have a single large factor */
@@ -2457,6 +2461,12 @@ print_factors_single (uintmax_t t1, uintmax_t t0)
       {
         lbuf_putc (' ');
         print_uintmaxes (0, factors.p[j]);
+        if (print_exponents && factors.e[j] > 1)
+          {
+            lbuf_putc ('^');
+            lbuf_putint (factors.e[j], 0);
+            break;
+          }
       }
 
   if (factors.plarge[1])
@@ -2525,6 +2535,11 @@ print_factors (char const *input)
       {
         putchar (' ');
         mpz_out_str (stdout, 10, factors.p[j]);
+        if (print_exponents && factors.e[j] > 1)
+          {
+            printf ("^%lu", factors.e[j]);
+            break;
+          }
       }
 
   mp_factor_clear (&factors);
@@ -2551,6 +2566,10 @@ Print the prime factors of each specified integer 
NUMBER.  If none\n\
 are specified on the command line, read them from standard input.\n\
 \n\
 "), stdout);
+      fputs ("\
+  -e, --exponents   print factors in the form x^y instead of repeating\n\
+                      the prime x y times.\n\
+", stdout);
       fputs (HELP_OPTION_DESCRIPTION, stdout);
       fputs (VERSION_OPTION_DESCRIPTION, stdout);
       emit_ancillary_info (PROGRAM_NAME);
@@ -2593,10 +2612,14 @@ main (int argc, char **argv)
   atexit (lbuf_flush);
 
   int c;
-  while ((c = getopt_long (argc, argv, "", long_options, NULL)) != -1)
+  while ((c = getopt_long (argc, argv, "e", long_options, NULL)) != -1)
     {
       switch (c)
         {
+        case 'e':
+          print_exponents = true;
+          break;
+
         case DEV_DEBUG_OPTION:
           dev_debug = true;
           break;
-- 
2.31.1




reply via email to

[Prev in Thread] Current Thread [Next in Thread]