1
$\begingroup$

Quite a simple question, I reckon, however, even quite an extensive search hasn't helped me.

I want to define a recursively defined sequence that starts with defined f[1] and f[2] and distinguishes the input like so: f[3k], f[3k+1], f[3k+2]. Each of these would have its own expression.

For further clarification, an example: $$ f(3n) = f(n)+1 $$ $$ f(3n+1) = f(n)+2 $$ $$ f(3n+2) = f(n)+3 $$ How does one go about that? I do know how to write simple recursion formulas on the level of Fibonacci or a factorial, it's only the distinguishing the input part. Also, this should be possible without any if statements, etc.

Thanks for any help!

$\endgroup$
0

1 Answer 1

3
$\begingroup$

You can simply define an expression for each such pattern, using Condition (shorthand: /;) to specify that it should only match in the appropriate cases. I'm assuming by f[3k] you mean some input that's fully divisible by 3, so I'd write:

f[1] = 0;
f[2] = 0;
f[x_] /; Mod[x, 3] === 0 := {"3k def",f[x-1]}
f[x_] /; Mod[x - 1, 3] === 0 := {"3k def",f[x-1]}
f[x_] /; Mod[x - 2, 3] === 0 := "{"3k def",f[x-1]}

f[6]
(* {"3k def", {"3k+2 def", {"3k+1 def", {"3k def", 0}}}} *)
$\endgroup$
2
  • $\begingroup$ Sorry I wasn't clear enough, however, this looks like it should be the solution! Thanks, I shall try that now and then report. $\endgroup$
    – Dahn
    Jan 28, 2013 at 10:56
  • $\begingroup$ Yes, this is exactly what I needed. Thanks! $\endgroup$
    – Dahn
    Jan 28, 2013 at 11:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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