Fraction reduction: Difference between revisions

From Rosetta Code
Content added Content deleted
m (added two terms that this method is also known as.)
m (added another AKA term.)
Line 67: Line 67:
;References:
;References:
:*   Wikipedia entry:   [https://en.wikipedia.org/wiki/Fraction_(mathematics)#Proper_and_improper_fractions proper and improper fractions].
:*   Wikipedia entry:   [https://en.wikipedia.org/wiki/Fraction_(mathematics)#Proper_and_improper_fractions proper and improper fractions].
:*   Wikipedia entry:   [https://en.wikipedia.org/wiki/Anomalous_cancellation anomalous cancellation].
:*   Wikipedia entry:   [https://en.wikipedia.org/wiki/Anomalous_cancellation anomalous cancellation and/or accidental cancellation].
<br><br>
<br><br>



Revision as of 09:43, 4 September 2019

Fraction reduction is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.
              There is a fine line between numerator and denominator.       ─── anonymous


A method to   "reduce"   some reducible fractions is to   cross out   a digit from the numerator and the denominator.   An example is:

       16                                                  16
      ────     and then (simply) cross─out the sixes:      ────
       64                                                  64

resulting in:

        1
       ───    
        4


Naturally,   this "method" of reduction must reduce to the proper value   (shown as a fraction).

This "method" is also known as   anomalous cancellation   and also   accidental cancellation.


(Of course,   this "method" shouldn't be taught to impressionable or gullible minds.)       😇


Task

Find and show some fractions that can be reduced by the above "method".

  •   show 2-digit fractions found   (like the example shown above)
  •   show 3-digit fractions
  •   show 4-digit fractions
  •   show 5-digit fractions   (and higher)       (optional)
  •   show each (above) n-digit fractions separately from other different n-sized fractions, don't mix different "sizes" together
  •   for each "size" fraction,   only show a dozen examples   (the 1st twelve found)
  •   (it's recognized that not every programming solution will have the same generation algorithm)
  •   for each "size" fraction:
  •   show a count of how many reducible fractions were found.   The example (above) is size 2
  •   show a count of which digits were crossed out   (one line for each different digit)
  •   for each "size" fraction,   show a count of how many were found.   The example (above) is size 2
  •   show each n-digit example   (to be shown on one line):
  •   show each n-digit fraction
  •   show each reduced n-digit fraction
  •   show what digit was crossed out for the numerator and the denominator


Task requirements/restrictions
  •   only proper fractions and their reductions   (the result)   are to be used   (no vulgar fractions)
  •   only positive fractions are to be used   (no negative signs anywhere)
  •   only base ten integers are to be used for the numerator and denominator
  •   no zeros   (decimal digit)   can be used within the numerator or the denominator
  •   the numerator and denominator should be composed of the same number of digits
  •   no digit can be repeated in the numerator
  •   no digit can be repeated in the denominator
  •   (naturally)   there should be a shared decimal digit in the numerator   and   the denominator
  •   fractions can be shown as   16/64   (for example)


Show all output here, on this page.


Somewhat related task

Farey sequence.


References



Go

This isn't particularly fast taking just under 2.5 minutes (all but a few seconds on the 5-digit fractions) to complete on my Celeron @1.6GHz. It would, of course, be much quicker on a modern machine. <lang go>package main

import "fmt" import "time"

func indexOf(n int, s []int) int {

   for i, j := range s {
       if n == j {
           return i
       }
   }
   return -1

}

func getDigits(n, le int, digits []int) bool {

   for n > 0 {
       r := n % 10
       if r == 0 || indexOf(r, digits) >= 0 {
           return false
       }
       le--
       digits[le] = r
       n /= 10
   }
   return true

}

var pows = [4]int{1, 10, 100, 1000}

func removeDigit(digits []int, le, idx int) int {

   sum := 0
   pow := pows[le-2]
   for i := 0; i < le; i++ {
       if i == idx {
           continue
       }
       sum += digits[i] * pow
       pow /= 10
   }
   return sum

}

func main() {

   start := time.Now()
   lims := [4][3]int{
       {12, 97, 98},
       {123, 986, 987},
       {1234, 9875, 9876},
       {12345, 98764, 98765},
   }
   var count [4]int
   var omitted [4][10]int
   for i, lim := range lims {
       nDigits := make([]int, i+2)
       dDigits := make([]int, i+2)
       blank := make([]int, i+2)
       for n := lim[0]; n <= lim[1]; n++ {
           copy(nDigits, blank)
           nOk := getDigits(n, i+2, nDigits)
           if !nOk {
               continue
           }
           for d := n + 1; d <= lim[2]; d++ {
               copy(dDigits, blank)
               dOk := getDigits(d, i+2, dDigits)
               if !dOk {
                   continue
               }
               for nix, digit := range nDigits {
                   if dix := indexOf(digit, dDigits); dix >= 0 {
                       rn := removeDigit(nDigits, i+2, nix)
                       rd := removeDigit(dDigits, i+2, dix)
                       if float64(n)/float64(d) == float64(rn)/float64(rd) {
                           count[i]++
                           omitted[i][digit]++
                           if count[i] <= 12 {
                               fmt.Printf("%d/%d = %d/%d by omitting %d's\n", n, d, rn, rd, digit)
                           }
                       }
                   }
               }
           }
       }
       fmt.Println()
   }
   for i := 2; i <= 5; i++ {
       fmt.Printf("There are %d %d-digit fractions of which:\n", count[i-2], i)
       for j := 1; j <= 9; j++ {
           if omitted[i-2][j] == 0 {
               continue
           }
           fmt.Printf("%6d have %d's omitted\n", omitted[i-2][j], j)
       }
       fmt.Println()
   }
   fmt.Printf("Took %s\n", time.Since(start))

}</lang>

Output:
16/64 = 1/4 by omitting 6's
19/95 = 1/5 by omitting 9's
26/65 = 2/5 by omitting 6's
49/98 = 4/8 by omitting 9's

132/231 = 12/21 by omitting 3's
134/536 = 14/56 by omitting 3's
134/938 = 14/98 by omitting 3's
136/238 = 16/28 by omitting 3's
138/345 = 18/45 by omitting 3's
139/695 = 13/65 by omitting 9's
143/341 = 13/31 by omitting 4's
146/365 = 14/35 by omitting 6's
149/298 = 14/28 by omitting 9's
149/596 = 14/56 by omitting 9's
149/894 = 14/84 by omitting 9's
154/253 = 14/23 by omitting 5's

1234/4936 = 124/496 by omitting 3's
1239/6195 = 123/615 by omitting 9's
1246/3649 = 126/369 by omitting 4's
1249/2498 = 124/248 by omitting 9's
1259/6295 = 125/625 by omitting 9's
1279/6395 = 127/635 by omitting 9's
1283/5132 = 128/512 by omitting 3's
1297/2594 = 127/254 by omitting 9's
1297/3891 = 127/381 by omitting 9's
1298/2596 = 128/256 by omitting 9's
1298/3894 = 128/384 by omitting 9's
1298/5192 = 128/512 by omitting 9's

12349/24698 = 1234/2468 by omitting 9's
12356/67958 = 1236/6798 by omitting 5's
12358/14362 = 1258/1462 by omitting 3's
12358/15364 = 1258/1564 by omitting 3's
12358/17368 = 1258/1768 by omitting 3's
12358/19372 = 1258/1972 by omitting 3's
12358/21376 = 1258/2176 by omitting 3's
12358/25384 = 1258/2584 by omitting 3's
12359/61795 = 1235/6175 by omitting 9's
12364/32596 = 1364/3596 by omitting 2's
12379/61895 = 1237/6185 by omitting 9's
12386/32654 = 1386/3654 by omitting 2's

There are 4 2-digit fractions of which:
     2 have 6's omitted
     2 have 9's omitted

There are 122 3-digit fractions of which:
     9 have 3's omitted
     1 have 4's omitted
     6 have 5's omitted
    15 have 6's omitted
    16 have 7's omitted
    15 have 8's omitted
    60 have 9's omitted

There are 660 4-digit fractions of which:
    14 have 1's omitted
    25 have 2's omitted
    92 have 3's omitted
    14 have 4's omitted
    29 have 5's omitted
    63 have 6's omitted
    16 have 7's omitted
    17 have 8's omitted
   390 have 9's omitted

There are 5087 5-digit fractions of which:
    75 have 1's omitted
    40 have 2's omitted
   376 have 3's omitted
    78 have 4's omitted
   209 have 5's omitted
   379 have 6's omitted
   591 have 7's omitted
   351 have 8's omitted
  2988 have 9's omitted

Took 2m24.172745543s

Perl 6

Works with: Rakudo version 2019.07.1
Anomalous Cancellation

<lang perl6>my %reduced; my $digits = 2..4;

for $digits.map: * - 1 -> $exp {

   my $start = sum (0..$exp).map( { 10 ** $_ * ($exp - $_ + 1) });
   my $end   = 10**($exp+1) - sum (^$exp).map( { 10 ** $_ * ($exp - $_) } ) - 1;
   ($start ..^ $end).race(:8degree, :3batch).map: -> $den {
       next if $den.contains: '0';
       next if $den.comb.unique <= $exp;
       for $start ..^ $den -> $num {
           next if $num.contains: '0';
           next if $num.comb.unique <= $exp;
           my $set = ($den.comb.head(* - 1).Set ∩ $num.comb.skip(1).Set);
           next if $set.elems < 1;
           for $set.keys {
               my $ne = $num.trans: $_ => , :delete;
               my $de = $den.trans: $_ => , :delete;
               if $ne / $de == $num / $den {
                   print "\b" x 40, "$num/$den:$_ => $ne/$de";
                   %reduced{"$num/$den:$_"} = "$ne/$de";
               }
           }
       }
   }


   print "\b" x 40, ' ' x 40, "\b" x 40;
   my $digit = $exp +1;
   my %d = %reduced.pairs.grep: { .key.chars == ($digit * 2 + 3) };
   say "\n({+%d}) $digit digit reduceable fractions:";
   for 1..9 {
       my $cnt = +%d.pairs.grep( *.key.contains: ":$_" );
       next unless $cnt;
       say "  $cnt with removed $_";
   }
   say "\n  12 Random (or all, if less) $digit digit reduceable fractions:";
   say "    {.key.substr(0, $digit * 2 + 1)} => {.value} removed {.key.substr(* - 1)}"
     for %d.pairs.pick(12).sort;

}</lang>

Sample output:
(4) 2 digit reduceable fractions:
  2 with removed 6
  2 with removed 9

  12 Random (or all, if less) 2 digit reduceable fractions:
    16/64 => 1/4 removed 6
    19/95 => 1/5 removed 9
    26/65 => 2/5 removed 6
    49/98 => 4/8 removed 9

(122) 3 digit reduceable fractions:
  9 with removed 3
  1 with removed 4
  6 with removed 5
  15 with removed 6
  16 with removed 7
  15 with removed 8
  60 with removed 9

  12 Random (or all, if less) 3 digit reduceable fractions:
    149/298 => 14/28 removed 9
    154/352 => 14/32 removed 5
    165/264 => 15/24 removed 6
    176/275 => 16/25 removed 7
    187/286 => 17/26 removed 8
    194/291 => 14/21 removed 9
    286/385 => 26/35 removed 8
    286/682 => 26/62 removed 8
    374/572 => 34/52 removed 7
    473/572 => 43/52 removed 7
    492/984 => 42/84 removed 9
    594/693 => 54/63 removed 9

(660) 4 digit reduceable fractions:
  14 with removed 1
  25 with removed 2
  92 with removed 3
  14 with removed 4
  29 with removed 5
  63 with removed 6
  16 with removed 7
  17 with removed 8
  390 with removed 9

  12 Random (or all, if less) 4 digit reduceable fractions:
    1348/4381 => 148/481 removed 3
    1598/3196 => 158/316 removed 9
    1783/7132 => 178/712 removed 3
    1978/5934 => 178/534 removed 9
    2971/5942 => 271/542 removed 9
    2974/5948 => 274/548 removed 9
    3584/4592 => 384/492 removed 5
    3791/5798 => 391/598 removed 7
    3968/7936 => 368/736 removed 9
    4329/9324 => 429/924 removed 3
    4936/9872 => 436/872 removed 9
    6327/8325 => 627/825 removed 3

REXX

<lang rexx>/*REXX pgm reduces fractions by "crossing out" matching digits in nominator&denominator.*/ parse arg high show . /*obtain optional arguments from the CL*/ if high== | high=="," then high= 4 /*Not specified? Then use the default.*/ if show== | show=="," then show= 12 /* " " " " " " */ say center(' some samples of reduced fractions by crossing out digits ', 79, "═") $.=0 /*placeholder array for counts; init. 0*/

     do L=2  to high;      say                  /*do 2-dig fractions to HIGH-dig fract.*/
                           lim= 10**L - 1       /*calculate the upper limit just once. */
        do n=10**(L-1)  to lim                  /*generate some  N  digit  fractions.  */
        if pos(0, n) \==0  then iterate         /*Does  it  have a zero?  Then skip it.*/
        if hasDup(n)       then iterate         /*  "    "    "  " dup?     "    "   " */
           do d=n+1     to lim                           /*only process like-sized #'s */
           if pos(0, d)\==0         then iterate         /*Have a zero? Then skip it.  */
           if verify(d, n, 'M')==0  then iterate         /*No digs in common?  Skip it.*/
           if hasDup(d)             then iterate         /*Any digs are dups?    "   " */
           q= n/d                                        /*compute quotient just once. */
                 do e=1  for L;     xo= substr(n, e, 1)  /*try crossing out each digit.*/
                 nn= space( translate(n, , xo), 0)       /*elide from the numerator.   */
                 dd= space( translate(d, , xo), 0)       /*  "     "   "  denominator. */
                 if nn/dd \== q  then iterate            /*Not the same quotient? Skip.*/
                 $.L=    $.L    + 1                      /*Eureka!   We found one.     */
                 $.L.xo= $.L.xo + 1                      /*count the silly reduction.  */
                 if $.L>show  then iterate               /*Too many found?  Don't show.*/
                 say center(n'/'d   " = "   nn'/'dd  "  by crossing out the" xo"'s.", 79)
                 end   /*e*/
           end         /*d*/
        end            /*n*/
     end               /*L*/

say; @with= ' with crossed-out' /* [↓] show counts for any reductions.*/

     do k=1  for 9                              /*traipse through each cross─out digit.*/
     if $.k==0  then iterate                    /*Is this a zero count?  Then skip it. */
     say;    say center('There are '     $.k     " "k'-digit fractions.', 79, "═")
                         @for= '          For ' /*literal for SAY indentation (below). */
        do #=1  for 9;   if $.k.#==0  then iterate
        say @for    k"-digit fractions, there are "    right($.k.#, k-1)   @with   #"'s."
        end   /*#*/
     end      /*k*/

exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ hasDup: parse arg x; /* if L<2 then return 0 */ /*L will never be 1.*/

          do i=1  for L-1;      if pos(substr(x,i,1), substr(x,i+1)) \== 0  then return 1
          end   /*i*/;                                                           return 0</lang>
output   when using the input of:     5   12
══════════ some samples of reduced fractions by crossing out digits ═══════════

                   16/64  =  1/4   by crossing out the 6's.
                   19/95  =  1/5   by crossing out the 9's.
                   26/65  =  2/5   by crossing out the 6's.
                   49/98  =  4/8   by crossing out the 9's.

                 132/231  =  12/21   by crossing out the 3's.
                 134/536  =  14/56   by crossing out the 3's.
                 134/938  =  14/98   by crossing out the 3's.
                 136/238  =  16/28   by crossing out the 3's.
                 138/345  =  18/45   by crossing out the 3's.
                 139/695  =  13/65   by crossing out the 9's.
                 143/341  =  13/31   by crossing out the 4's.
                 146/365  =  14/35   by crossing out the 6's.
                 149/298  =  14/28   by crossing out the 9's.
                 149/596  =  14/56   by crossing out the 9's.
                 149/894  =  14/84   by crossing out the 9's.
                 154/253  =  14/23   by crossing out the 5's.

               1234/4936  =  124/496   by crossing out the 3's.
               1239/6195  =  123/615   by crossing out the 9's.
               1246/3649  =  126/369   by crossing out the 4's.
               1249/2498  =  124/248   by crossing out the 9's.
               1259/6295  =  125/625   by crossing out the 9's.
               1279/6395  =  127/635   by crossing out the 9's.
               1283/5132  =  128/512   by crossing out the 3's.
               1297/2594  =  127/254   by crossing out the 9's.
               1297/3891  =  127/381   by crossing out the 9's.
               1298/2596  =  128/256   by crossing out the 9's.
               1298/3894  =  128/384   by crossing out the 9's.
               1298/5192  =  128/512   by crossing out the 9's.

             12349/24698  =  1234/2468   by crossing out the 9's.
             12356/67958  =  1236/6798   by crossing out the 5's.
             12358/14362  =  1258/1462   by crossing out the 3's.
             12358/15364  =  1258/1564   by crossing out the 3's.
             12358/17368  =  1258/1768   by crossing out the 3's.
             12358/19372  =  1258/1972   by crossing out the 3's.
             12358/21376  =  1258/2176   by crossing out the 3's.
             12358/25384  =  1258/2584   by crossing out the 3's.
             12359/61795  =  1235/6175   by crossing out the 9's.
             12364/32596  =  1364/3596   by crossing out the 2's.
             12379/61895  =  1237/6185   by crossing out the 9's.
             12386/32654  =  1386/3654   by crossing out the 2's.


═══════════════════════There are  4  2-digit fractions.════════════════════════
          For  2-digit fractions, there are  2  with crossed-out 6's.
          For  2-digit fractions, there are  2  with crossed-out 9's.

══════════════════════There are  122  3-digit fractions.═══════════════════════
          For  3-digit fractions, there are   9  with crossed-out 3's.
          For  3-digit fractions, there are   1  with crossed-out 4's.
          For  3-digit fractions, there are   6  with crossed-out 5's.
          For  3-digit fractions, there are  15  with crossed-out 6's.
          For  3-digit fractions, there are  16  with crossed-out 7's.
          For  3-digit fractions, there are  15  with crossed-out 8's.
          For  3-digit fractions, there are  60  with crossed-out 9's.

══════════════════════There are  660  4-digit fractions.═══════════════════════
          For  4-digit fractions, there are   14  with crossed-out 1's.
          For  4-digit fractions, there are   25  with crossed-out 2's.
          For  4-digit fractions, there are   92  with crossed-out 3's.
          For  4-digit fractions, there are   14  with crossed-out 4's.
          For  4-digit fractions, there are   29  with crossed-out 5's.
          For  4-digit fractions, there are   63  with crossed-out 6's.
          For  4-digit fractions, there are   16  with crossed-out 7's.
          For  4-digit fractions, there are   17  with crossed-out 8's.
          For  4-digit fractions, there are  390  with crossed-out 9's.

══════════════════════There are  5087  5-digit fractions.══════════════════════
          For  5-digit fractions, there are    75  with crossed-out 1's.
          For  5-digit fractions, there are    40  with crossed-out 2's.
          For  5-digit fractions, there are   376  with crossed-out 3's.
          For  5-digit fractions, there are    78  with crossed-out 4's.
          For  5-digit fractions, there are   209  with crossed-out 5's.
          For  5-digit fractions, there are   379  with crossed-out 6's.
          For  5-digit fractions, there are   591  with crossed-out 7's.
          For  5-digit fractions, there are   351  with crossed-out 8's.
          For  5-digit fractions, there are  2988  with crossed-out 9's.