0
$\begingroup$

Two sets

x = 1,2,3,4,5... y = 1,4,7,10,13... 

I need to write a function

$f(x_n) = y_n$

I found that if I

  1. take a number from x
  2. double it
  3. subtract 2
  4. add the result to the original number
  5. I get the corresponding number from y

Here's what I have so far (it's in ruby code), it works but is there a better way of doing it.

def f(x)   if x > 1     return x + ((2 * x) - 2)   else     return 1   end end  y = f(x) 
  • 0
    Not sure what better way you are looking for. What you have seems fine, expect we can multiply by 3 instead of doubling and then adding itself. I guess Ruby does not have overflow issues.2011-01-09

1 Answers 1

3

Your values y form what is called an arithmetic progression, namely a sequence where each element is obtained from the previous one just by adding always the same constant. In your case the constant is 3, namely: 1, 4=1+3, 7=4+3, 10=7+3 and so on.

Since the FIRST time you add 3 corresponds to x=2, the formula is just

y=1+3*(x-1)

or (equivalently)

y=3*x-2.

  • 0
    Wow thanks, I can't believe I didn't think about 3x instead of $2$x + x lol.2011-01-09