0

print the first 5 members of the array a[n+1]=3*a[n]+7 which don't contain the number 5.

a1=6.

so a[2]=3*6+7=25, but 25 has the number 5 so we go to a[3].

a[3]=25*3+7=82 <--- this is OK... and so on until we print 5 members.

enter image description here

these should be the printed members.

2 Answers2

7

The recurrence equation can be solved analytically

Clear[a]

a[n_] = a[n] /.
  RSolve[
    {a[n + 1] == 3 a[n] + 7, a[1] == 6}
    , a[n], n][[1]]

(1/6)*(-21 + 19*3^n)

Generate a sufficiently long starting list, Select numbers that do not contain the digit 5, and Take the first five elements of the remaining list.

Take[
   Select[
    Table[{n, a[n]}, {n, 10}]
    , ! MemberQ[IntegerDigits[#[[2]]], 5] &]
   , 5] //
  Prepend[#, {"n", "a[n]"}] & //
 Grid

enter image description here

Bob Hanlon
  • 157,611
  • 7
  • 77
  • 198
  • 1
    One could also use DigitCount[#, 10, 5] == 0 & as the selection function. – J. M.'s missing motivation May 19 '15 at 18:29
  • 1
    @Guesswhoitis I find a bit of a speed penalty with the DigitCount approach though: MemberQ@IntegerDigits seems roughly 10x faster. MemberQ may be smart enough to stop as soon as it can determine its own truth value (i.e. when it finds the first 5 in the IntegerDigits list), so it doesn't have to traverse the whole list every time. On the other hand, DigitCount has no choice but to look at the whole list of digits (i.e. it calls Tally on the IntegerDigits list). I wonder if that's really why... – MarcoB May 19 '15 at 18:48
  • 1
    @Marco, interesting; I haven't looked at the time difference. Sounds like a good question… :) – J. M.'s missing motivation May 19 '15 at 19:00
1
fun[n_] := 
 Reap[NestList[Sow[3 # + 7, FreeQ[IntegerDigits[3 # + 7],5]] &, Sow[6, True], 
    n],True][[2, 1]]

This will produce the numbers that comply,e.g. fun[10]:

{6, 82, 766, 6922, 20773, 62326}

If the n is desired:

funq[n_] := 
 Reap[NestList[
    Sow[{#[[1]] + 1, 3 #[[2]] + 7},  FreeQ[IntegerDigits[3 #[[2]]+7],5]] &, 
    Sow[{1, 6}, True], n], True][[2, 1]]

e.g. Grid[Prepend[funq[10], {"n", "a[n]"}]]

ubpdqn
  • 60,617
  • 3
  • 59
  • 148