Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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!

share|improve this question
add comment

1 Answer 1

up vote 3 down vote accepted

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}}}} *)
share|improve this answer
    
Sorry I wasn't clear enough, however, this looks like it should be the solution! Thanks, I shall try that now and then report. –  Dahn Jahn Jan 28 '13 at 10:56
    
Yes, this is exactly what I needed. Thanks! –  Dahn Jahn Jan 28 '13 at 11:19
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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