2005-09-28

Rational Reduction

I have an algorithm that I think I need to write in TI-BASIC. The algorithm attempts to reduce a positive fraction, i.e. 16/64 becomes 1/4. I'm not entirely sure if this algorithm is correct, but I'm posting it here anyway so I don't lose it.

  1. Take two integers as input, N and D.
  2. Factor N and D (currently, my idea is to use repeated trial division, which I'd already written back in college as part of a Rabin-Miller program. In TI-BASIC. Aw, yeah.)
  3. Store the prime factors of N in a vector VN, and the prime factors of D in a vector VD. (No jokes, please.)

  4. For each I from 0 to length of VN:
      For each J from 0 to length of VD:
        A = VN[I]
        B = VD[J]
    
        If (B > A) Then
          J = 9999
        EndIf
    
        If (B == A) Then
          VN[I] = 0
          VD[J] = 0
          J = 9999
        EndIf


  5. X = 1
    Y = 1
    
    For each I from 0 to length of VN:
      A = VN[i]
      If (A > 0) Then
        X = X * A
      EndIf
    
    For each J from 0 to length of VD:
      B = VN[i]
      If (B > 0) Then
        Y = Y * B
      EndIf


  6. Output X and Y.

Example: 16 / 64

N = 16
D = 64
VN = [2 2 2 2]
VD = [2 2 2 2 2 2]

VN would become [0 0 0 0]
VD would become [0 0 0 0 2 2]
X = 1
Y = 1 * 2 * 2 = 4

Thus, 16 / 64 is equal to 1 / 4.

Update: Nevermind. The TI-85 I'd be using already has a >Frac function that reduces fractions much faster than I could.

No comments: