0
$\begingroup$

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?

$\endgroup$
9
  • $\begingroup$ 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.) $\endgroup$
    – whuber
    Commented Mar 7, 2013 at 23:08
  • $\begingroup$ I rephrased the format of the question from Project Euler. The fraction is reduced before the function is re-applied. $\endgroup$
    – aaazalea
    Commented Mar 7, 2013 at 23:09
  • $\begingroup$ 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.) $\endgroup$
    – whuber
    Commented Mar 7, 2013 at 23:10
  • $\begingroup$ so I pass $x_i/y_i$ as $sofar$ and then determine the new numerator, then $\frac{num}{sofar}$ is $y_i$ $\endgroup$
    – aaazalea
    Commented Mar 7, 2013 at 23:11
  • 1
    $\begingroup$ @whuber After completely changing my code such that it works in the way you suggested, the problem goes away. Huh. Thanks. $\endgroup$
    – aaazalea
    Commented Mar 7, 2013 at 23:26

1 Answer 1

0
$\begingroup$

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

$\endgroup$

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