0

I'm relatively new to Mathematica, and I'm trying to define a function f(k) that would do the following:

For any positive integer $k$, a finite sequence $a_i$ of fractions $\frac{x_i}{y_i}$ is defined by: $$a_1 = \frac{1}{k}\\ a_i = \frac{x_{i-1}+1}{y_{i-1}-1}$$ When $a_i$ reaches some integer $n$, the sequence stops. (That is, when $y_i=1$.) Define $f(k) = n$.

-- Project Euler

I have the following function written:

f[k_, sofar_] = Module[{num, result},
  result =
   If[sofar == 0,1/k,((num = Numerator[sofar]) + 1)/(num/sofar - 1)
    ];
  If[IntegerQ[result],result,f[k,result]]
 ];
f[k_] = f[k, 0]

But I get the result {ComplexInfinity,List} and I don't understand why. What am I doing wrong?

whuber
  • 20,544
  • 2
  • 59
  • 111
  • Your function needs to depend on both $x_{i-1}$ and $y_{i-1}$. (This answer applies to any programming language you might choose for tackling this problem.) – whuber Mar 07 '13 at 23:08
  • I rephrased the format of the question from Project Euler. The fraction is reduced before the function is re-applied. – Jakob Weisblat Mar 07 '13 at 23:09
  • Yep, but you still need to track the numerator and denominator, so you might as well do so explicitly--at least conceptually. Your life will be much easier. (Mathematica can handle many of the details, but under the hood it will be doing exactly the same thing: carrying an ordered pair of (numerator, denominator) around.) – whuber Mar 07 '13 at 23:10
  • so I pass $x_i/y_i$ as $sofar$ and then determine the new numerator, then $\frac{num}{sofar}$ is $y_i$ – Jakob Weisblat Mar 07 '13 at 23:11
  • 1
    @whuber After completely changing my code such that it works in the way you suggested, the problem goes away. Huh. Thanks. – Jakob Weisblat Mar 07 '13 at 23:26
  • Just to get you started: f[q_] := (Numerator[q] + 1) / (Denominator[q] - 1) takes care of the basic iteration step. Read the manual page for NestWhile to find out how to stop the iteration. Generate an initial sequence of results and then look it up in the OEIS for an excellent additional hint (including more Mathematica code). – whuber Mar 07 '13 at 23:27
  • Mine's a bit more cumbersome, but all in one function: f[num_, denom_] = If[Mod[num, denom] == 0, num, f[(num + 1)/GCD[num + 1, denom - 1], (denom - 1)/ GCD[num + 1, denom - 1]]] f[x1_] = f[1, x1] – Jakob Weisblat Mar 07 '13 at 23:33
  • Did you manage to figure out how to solve your problem? – J. M.'s missing motivation Apr 27 '13 at 04:38
  • @JakobWeisblat Here's a perhaps more "Mathematica-idiomatic" form: next[{n_, d_} /; Divisible[n, d]] := n/d; next[{n_, d_}] := Module[{a = (n + 1)/(d - 1)}, {Numerator[a], Denominator[a]}];f[k_] := NestWhile[next, {1, k}, ListQ]; And here's what you might consider the ideal: f[n_] := n; f[Rational[n_, d_]] := f[(n + 1)/(d - 1)]; usage: f[1/n] – amr Apr 28 '13 at 05:25

1 Answers1

0

The solution to this problem is to use := instead of = with the function definition so that it is not evaluated immediately.