[Haskell-cafe] expension of fractions

Arie Groeneveld bradypus at xs4all.nl
Tue Jul 24 05:02:57 EDT 2007


Hi,

I don't know if this is the right place to post this, but here I go.

I translated a BC-program found on the home page of Keith Matthews,
http://www.numbertheory.org/keith.html.
It's about the expension of a (not necessarily reduced) fraction m/n in
base b.

Looking at the result of my rewriting gives me the idea it isn't
Haskelly enough.

Anyways, here's my interpretation:

-- period m/n base = (period length, preperiod digits, period digits)
period :: Integer -> Integer -> Integer -> (Int, ([Integer], [Integer]))
period m n base | m' >= n'  = error $ show m ++ " >= " ++ show  n
                | m' < 1    = error $ "m (" ++ show m ++ ") < 1"
                | n' < 1    = error $ "n (" ++ show n ++ ") < 1"
                | base <= 1 = error $ "base (" ++ show base ++ ") < 2"
                | otherwise = decimals [] [m']
    where g = gcd m n
          m' = m `div` g
          n' = n `div` g
          decimals qs rs | i' /= -1 = (length rs - i', splitAt i' qsi)
                          | otherwise = decimals qsi (rs++[ri])
             where (qi,ri) = divMod (base * last rs) n
                   i = findIndex (==ri) rs
                   i' = if i == Nothing then -1 else fromJust i
                   qsi = qs++[qi]



Which comes from the BC program:
(Keith Matthews)

define period(m,n,b){
    auto a[],g,i,p,j,c[]
   
    g=gcd(m,n)
    m=m/g;n=n/g
    if(m>=n){"m>=n:"; return(0)}
    if(m<1){"m<1:"; return(0)}
    if(n<1){"n<1:"; return(0)}
    if(b<=1){"b<=1:"; return(0)}
    i=0
        c[0]=m
        flag=0
    while(flag==0){
        p=b*c[i]
                i=i+1
        c[i]=p%n
                a[i]=p/n
        /*print "a[",i,"]=",a[i],"\n" /* the i-th digit */
                if(i==1000){
                   print "limit of 1000 digits produced\n"
                   return(0)
                }
                for(j=0;j<i;j++){
           if(c[i]==c[j]){
                      flag=1
                      break
                   }
                }
    }
print "the expansion of ",m,"/",n," to base ",b,"\n"
if(j){
    print "preperiod digits: "
    for(k=1;k<=j;k++){
       print a[k],","
    }
    print "\n"
}
print "period digits: "
for(k=j+1;k<=i;k++){
   print a[k]
   if(k<i){
      print ","
   }
}
print "\n"
t=i-j
"period-length = ";return(t)
}




More information about the Haskell-Cafe mailing list