Simplyfiying fractions in Javascript

D

Dr John Stockton

JRS: In article <[email protected]>
, dated Thu, 12 Jan 2006 17:52:27 local, seen in
news:comp.lang.javascript said:
Does anybody have a script to simplify fractions?

Let the fraction be X/Y, X & Y being variables.

function HCF(u, v) { var U = u, V = v
while (true) {
if (!(U%=V)) return V
if (!(V%=U)) return U } }

T = HCF(X, Y) ; X /= T ; Y /= T ;

HCF is used in js-dates.htm, via FAQ, see below. It is intended for use
only with positive integer parameters, but full compliance is not
obligatory.
 
R

Randy Webb

Dr John Stockton said the following on 1/13/2006 3:03 PM:
JRS: In article <[email protected]>
, dated Thu, 12 Jan 2006 17:52:27 local, seen in



Let the fraction be X/Y, X & Y being variables.

function HCF(u, v) { var U = u, V = v

Just for my own curiosity, does the U = u and V = v serve any useful
purpose? Meaning, does the code fail if you use u and v below instead of
U and V?

It shouldn't is why I am asking.
 
L

Lasse Reichstein Nielsen

Randy Webb said:
Dr John Stockton said the following on 1/13/2006 3:03 PM:

Just for my own curiosity, does the U = u and V = v serve any useful
purpose? Meaning, does the code fail if you use u and v below instead
of U and V?

Not in this case. Both "u" and "U" are local variables, and since "u"
is never used again, there is no immediate need to rename it.

I'm guessing it's a general strategy to avoid changing the parameters,
in case they are needed again later.

/L
 
D

Dr John Stockton

JRS: In article <[email protected]>, dated Fri, 13 Jan
2006 21:38:20 local, seen in Randy Webb
Dr John Stockton said the following on 1/13/2006 3:03 PM:

Just for my own curiosity, does the U = u and V = v serve any useful
purpose? Meaning, does the code fail if you use u and v below instead of
U and V?

It shouldn't is why I am asking.

Usually at least, ISTM that it will not fail. I converted it from
another language, in which there are three possible ways of passing
parameters and the one which copies must be used (another won't compile
with that body; the third will change the external quantities). I put
the copying in as being easier than deciding whether it might ever
matter.

The only javascript in which I at present use it is

F = A[0] ; J = N ; while (J--) F = HCF(F, A[J])

after which A is abandoned and F is displayed - so I'd not notice the
difference anyway even if there were any.

Code, in js-dates.htm, changed. Thanks.

<URL:http://www.merlyn.demon.co.uk/hcfactor.pas> has several HCF
algorithms.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top