8
\$\begingroup\$

When I was in grade 3, we were taught how to solve a very simple math problem. It was equaling the denominators of two or more fractions.

Let's take two proper fractions:-

$$ \frac{1}{2},\frac{2}{3} $$

First we will take the Least Common Multiple of the denominators of the two fractions, the LCM of \$2,3\$ are \$6\$. Then we divide the LCM (\$6\$) by the denominators of both fractions (\$6\$) and we get \$3,2\$ and serially multiply them with the numerators of the both fractions and get

$$ \frac{3}{6},\frac{4}{6} $$

And that's the result.

Challenge

Take two or more fractions, and equalize their denominators.

I/O format

You can take an array/list of (numerator,denominator) pairs. Pre-defining them in TIO header is allowed. You can take in other better ways too.

Input: ((1,2),(2,3)) or
        1,2 2,3
        1/2 2/3
Output: (3,6),(4,6) or 
        3,6 4,6 
        3/6 4/6
Input:  ((1, 8), (5, 12))
       1,8 5,12
       1/8 5/12
Output: ((3, 24), (10, 24))
         3,24 10,24
         3/24 10/24
Input: ((1, 2),(2, 3),(4, 6))
Output: 3/6 4/6 4/6

Rules

  • Standard loopholes are forbidden. (except use of TIO headers to pre-define input)
  • Trailing whitespace in output is allowed.
  • If possible, please link to an online interpreter (e.g. TIO) to run your program on.
  • Please explain your answer. This is not necessary, but it makes it easier for others to understand.
  • Languages newer than the question are allowed. This means you could create your own language where it would be trivial to do this, but don't expect any upvotes.
  • This is , so shortest code in bytes wins!
\$\endgroup\$
20
  • 7
    \$\begingroup\$ Sorry to bother again, but if non-simplified fractions can appear in the input (as it looks like from the last testcase), you may consider adding a testcase like 2/4, 3/6, where computing the LCM of the denominators is not enough. \$\endgroup\$
    – Delfad0r
    Apr 1 at 10:15
  • 5
    \$\begingroup\$ @Wasif You posted in the sandbox yesterday. Then you post today complaining that it might be treated as if you didn't post to the sandbox at all! T_T Wait a few days for feedback from the sandbox posting and then you won't be in such dilemma. \$\endgroup\$
    – Noodle9
    Apr 1 at 12:01
  • 6
    \$\begingroup\$ I'm voting to close as unclear because it's not apparent to me from the challenge how non-reduced fractions are handled. \$\endgroup\$
    – xnor
    Apr 1 at 14:15
  • 6
    \$\begingroup\$ You have many choices to clarity the question: 1. Change the rule to: Inputs will never contain non-reduced fractions (or input with non-reduced factions may lead to undefined behaviors), change last testcase to avoid it; 2. Clarity that input may contain non-reduced fractions, and answers should always use LCM of denominator, add a testcase (2/4, 3/6) -> (6/12, 6/12); 3. Clarity that input may contain no-reduced factions, and answers should not use LCM of denominator, but the smallest possible value, add a testcase (2/4, 3/6) -> (1/2, 1/2); \$\endgroup\$
    – tsh
    Apr 2 at 1:41
  • 6
    \$\begingroup\$ Also, you need to add your comment to "Are all numbers in the input positive integers" into the question. Not only leave it in comment. \$\endgroup\$
    – tsh
    Apr 2 at 1:42

15 Answers 15

7
\$\begingroup\$

JavaScript (Node.js), 63 bytes

f=(a,t=1)=>a.some(v=>t%v[1])?f(a,1+t):a.map(([p,q])=>[p*t/q,t])

Try it online!


JavaScript (Node.js), 63 bytes

f=(a,t,b=a.map(([p,q])=>[m=p*t/q,o&=m%1||t],o=t))=>o?b:f(a,-~t)

Try it online!

m=p*t/q cannot be changed to p*=t/q due to floating point errors. For example, 11*15/11 is 15, but 11*(15/11) is 14.999999999999998. :(

  • The first answer here will output [[6, 12], [6, 12]] for input [[2, 4], [3, 6]].
  • The second one will output [[1, 2], [1, 2]] for input [[2, 4], [3, 6]].

JavaScript (Node.js), 62 bytes

  • @Arnauld had modified the code to make it work in 62 bytes. This one would support positive fractions.
f=(a,t,o=-~t,b=a.map(([p,q])=>[p*t/q,t+=p*t%q]))=>t<o?b:f(a,o)

Try it online!

\$\endgroup\$
0
5
\$\begingroup\$

Wolfram Language (Mathematica), 20 bytes

LCM@@(q=Last/@#)/q#&

Try it online!

Fractions are in the form {numerator, denominator}
We simply multiply the fractions by the LCM of denominators divided by the denominators

\$\endgroup\$
5
\$\begingroup\$

Factor, 73 64 bytes

-9 bytes thanks to chunes!

[ dup 1 [ lcm ] reduce [ swap n/v v* dup length ] keep <array> ]

Try it online!

Takes the input as two separate lists for numerators and denominators

Factor, 73 bytes

[ unzip dup 1 [ lcm ] reduce swap over [ n/v v* ] dip '[ _ 2array ] map ]

Try it online!

Takes the input as a list of (numerator,denominator) pairs.

I thought it would be shorter using fractions but I didn't manage to make it nice. Except this the Factor version TIO has normalizes the fractions.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ We came up with similar answers, but I took the input as two separate lists for numerators and denominators. \$\endgroup\$
    – chunes
    Apr 1 at 12:27
  • \$\begingroup\$ @chunes Thanks for sharing! Feel free to post it as a separate submission. \$\endgroup\$ Apr 1 at 12:31
  • \$\begingroup\$ @chunes I updated the post using your solution - tahnks again! \$\endgroup\$ Apr 2 at 6:29
4
\$\begingroup\$

J, 14 10 bytes

,.**./@]%]

Try it online!

-4 after realizing taking a list of numerators and a list of denominators was allowed

Works like <list of numerators> f <list of denominators>.

  • *./@] LCM of denominators (right hand arg)...
  • %] Divided elementwise by the denominators...
  • ,.* Times the zip of the numerators and denominators.
\$\endgroup\$
3
\$\begingroup\$

Ruby, 57 bytes

->l{k=l.reduce(1){|s,x|s.lcm x[1]};l.map{|a,b|[a*k/b,k]}}

Try it online!

\$\endgroup\$
3
\$\begingroup\$

Jelly, 9 8 bytes

aæl/Ṅ:Ʋ×

Try it online!

Full program. Takes a list of denominators \$[d_1, d_2, ...]\$ on the left and a list of numerators \$[n_1, n_2, ...]\$ on the right. Outputs a list of denominators, then a list of numerators

Would be 7 bytes if we could just output the dominator once.

How it works

aæl/Ṅ:Ʋ× - Main link. Takes denominators D on the left and numerators N on the right
      Ʋ  - Group the previous 4 links into a monad on D:
 æl/     -   Reduce by LCM
a        -   AND; Replace each element in D with the LCM
    Ṅ    -   Print the list of LCM
     :   -   Divide each by the corresponding element of D
       × - Multiply this list with N elementwise
\$\endgroup\$
3
\$\begingroup\$

Haskell, 45 bytes

n#d=($d).zipWith(div.(*foldr1 lcm d))<$>[n,d]

Try it online!

Takes two lists (n=numerators and d=denominators) as input, returns two lists with the same format as output. Assumes fractions in the input are reduced.

Haskell, 72 69 66 bytes

f x|l<-foldr(\(n,d)->lcm.div d$gcd n d)1x=[(div(n*l)d,l)|(n,d)<-x]

Try it online!

Takes a list of pairs as input, returns a list of pairs as output. Works for unreduced fractions as well.

Haskell, 79 bytes

f x|let(z,l)=foldr(\(n,d)(y,a)->((div(n*l)d,l):y,lcm(d`div`gcd n d)a))([],1)x=z

Takes a list of pairs as input, returns a list of pairs as output. Works for unreduced fractions as well.

Quite a bit longer than the other answer, but I decided to post it anyway since there is some Haskell magic going on! The LCM of the (reduced) denominators l appears both on the left hand side and the right hand side of the let expression. This is only possible because of Haskell's lazyness.

\$\endgroup\$
2
\$\begingroup\$

Pyth, 33 bytes

K1JEFkJ=K/*kKikK;FkE[/*kKhJK)=JtJ

Try it online!

Takes two lines of input: first line should contain the list of denominators, and the second line should contain the list of corresponding numerators.

Explanation

K1       # Initialize K to 1
JE       # Initialize J to evaluated input (in this case, list of denominators)
FkJ      # For loop over elements of J, with iterator as k
=K       # Set K to
*kK      # Product of k and K
ikK      # GCD of k and K
/        # Divide them to get the LCM
FkE      # Another for loop over the next evaluated input (the numerators)
hJ       # First element of J
/*kKhJ   # Convert the numerator accordingly
K        # Denominator
[...)    # Put that inside a list and print it
tJ       # Tail J (first element removed)
=J       # Assign J to it
\$\endgroup\$
1
\$\begingroup\$

Python 3, 99 bytes

import numpy
f=lambda a,i=0,k=1:i<len(a)and f(a,i+1,numpy.lcm(k,a[i][1]))or[(p*k//q,k)for p,q in a]

Try it online!

Takes a list of lists and computes the LCM of denominators. This result is stored in k and at the end the fractions are converted to the same denominator (k).

\$\endgroup\$
0
1
\$\begingroup\$

Retina, 82 bytes

\d+
*
+`(_+)/((_+)(\3)*) (_+)/(?!\2\b)(\3)+\b
$#6*$1/$#6*$2 $#4*$5$5/$#6*$2
_+
$.&

Try it online! Link includes test cases. Explanation:

\d+
*

Convert to unary.

+`

Repeat until all denominators are equal.

(_+)

Match a numerator...

/((_+)(\3)*)

... and the largest factor of a denominator...

 (_+)

... and another numerator...

/(?!\2\b)(\3)+\b

... and a denominator that is not equal to the first denominator but with the shared (greatest) common divisor.

$#6*$1/$#6*$2 $#4*$5$5/$#6*$2

Multiply the first fraction by the multiplicity $#6 of the GCD in the second fraction, and also update the second fraction.

_+
$.&

Convert to decimal.

\$\endgroup\$
1
\$\begingroup\$

Charcoal, 30 bytes

≔Eθ⊟ιη≔¹ζW⌈﹪ζη≦⊕ζIEθ⟦÷×ζ⊟ι§ηκζ

Try it online! Link is to verbose version of code. I/O is standard Charcoal array format. Explanation: Uses brute force.

≔Eθ⊟ιη

Get the denominators.

≔¹ζ

Assume the LCM is 1.

W⌈﹪ζη≦⊕ζ

Keep incrementing the LCM until all the denominators divide it.

IEθ⟦÷×ζ⊟ι§ηκζ

Scale the fractions to the new denominator.

\$\endgroup\$
1
\$\begingroup\$

R, 69 66 bytes

Edit: -3 bytes thanks to Giuseppe

function(m)m/m[,2]*which(!rowSums(outer(1:prod(m),m[,2],"%%")))[1]

Try it online!

Input & output as 2-column matrices, with each row representing a pair of numerator & denominator.

\$\endgroup\$
2
  • \$\begingroup\$ 66 bytes \$\endgroup\$
    – Giuseppe
    Apr 6 at 21:07
  • \$\begingroup\$ @Giuseppe - Thanks. Nice exploitation of which bringing the elements into-order to avoid the need for min. I like it. \$\endgroup\$ Apr 8 at 17:53
0
\$\begingroup\$

Excel, 130 bytes

=LET(n,COUNT(A:A),b,OFFSET(B1,,,n),q,SEQUENCE(PRODUCT(b)),MIN(IF(MMULT(1*(MOD(q,TRANSPOSE(b))=0),b^0)=n,q,""))/b*OFFSET(A1,,,n,2))

Uses columns A&B for input

=LET(
n,COUNT(A:A)                                                            ' Number of fractions
b,OFFSET(B1,,,n)                                                        ' List of denominators
q,SEQUENCE(PRODUCT(b))                                                  ' 1..product of all denominators
MIN(IF(MMULT(1*(MOD(q,TRANSPOSE(b))=0),b^0)=n,q,""))/b*OFFSET(A1,,,n,2) ' final calculation
             1*(MOD(q,TRANSPOSE(b))=0)                                  ' matrix of q by b where 1 indicates q mod b = 0
    IF(MMULT(                         ,b^0)=n,q,"")                     ' if q is divisible by all n numbers then q else "" (list of all common multiples)
MIN(                                               )                    ' least common multiple
                                                    /b*OFFSET(A1,,,n,2) ' multiply each row by the number need to change denominator to LCM
\$\endgroup\$
0
\$\begingroup\$

05AB1E, 9 bytes

.¿©¹÷*®δ‚

Input as two separated lists, first the list of denominator, second the list of numerator.
Output as a list of pairs of [numerator, denominator].

Try it online or verify all test cases.

Explanation:

.¿         # Get the Least Common Multiple (LCM) of the first (implicit) input-list of 
           # denominators
  ©        # Store this value in variable `®` (without popping)
   ¹÷      # Integer-divide it by each value of the first input-list
     *     # Multiply each value at the same positions to the second (implicit)
           # input-list of numerators
       δ   # For each value:
      ® ‚  #  Pair it with the stored LCM of variable `®`
           # (after which the resulting list of pairs is output implicitly as result)
\$\endgroup\$
0
\$\begingroup\$

Julia, 22 bytes

n$d=(l=lcm(d))n./d.=>l

Try it online!

  • expects [numerators] $ [denominators]
  • outputs an array of pairs : [num1 => den1, num2 => den2,...]
  • could be 20 bytes with the denominator only once in the ouput
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.