## Cow 15

For other topics related to the FreeBASIC project or its community.
srvaldez
Posts: 1893
Joined: Sep 25, 2005 21:54

### Cow 15

found this problem in Quantum Magazine V9N4
Dr. Mu wrote:Cow 15
Write a program that generates the terms in the sequence 1, 2, 3, 6, 4, 8, 5, 10, 7, 14, 9, 18,. . . . Test it by finding the 100,000th term. Speed and elegance count.

anyone want to try ?
lizard
Posts: 440
Joined: Oct 17, 2017 11:35
Location: Germany

### Re: Cow 15

This?

Code: Select all

`' cow.basdim as short used(100000)for i as integer = 1 to 100000  if not used(i) then print i, i*2, : used(i*2) = -1next i  `
lizard
Posts: 440
Joined: Oct 17, 2017 11:35
Location: Germany

### Re: Cow 15

Or this?

Code: Select all

`' cow2.basdim shared as short used(1000000)dim as integer i,edo  i += 1  if not used(i) then     print i, i*2,     used(i*2) = -1    e += 1  endifloop until e = 100000print:printprint "100000th =" ,i `
Last edited by lizard on Feb 02, 2018 20:10, edited 1 time in total.
srvaldez
Posts: 1893
Joined: Sep 25, 2005 21:54

### Re: Cow 15

you are very close, I edited your first try to give the desired result

Code: Select all

`dim as short used(150000)dim as long c=1, i=1while c<=50000 'only need half of 100,000 because numbers come in pairs  if not used(i) then print i, i*2, : used(i*2) = -1:c+=1  i+=1wend `
lizard
Posts: 440
Joined: Oct 17, 2017 11:35
Location: Germany

### Re: Cow 15

Great.
srvaldez
Posts: 1893
Joined: Sep 25, 2005 21:54

### Re: Cow 15

can you think of a recursive solution instead of using an array ?
lizard
Posts: 440
Joined: Oct 17, 2017 11:35
Location: Germany

### Re: Cow 15

Difficult, i always use arrays.
dodicat
Posts: 5703
Joined: Jan 10, 2006 20:30
Location: Scotland

### Re: Cow 15

Code: Select all

`sub calc(n as long,lim as long)    static as long counter    counter+=2    print n;2*n,    if counter=lim then exit sub   if n mod 3 =0 or n mod 4=0 then calc(n+1,lim) else calc(n+2,lim)end subcalc 1,100sleep  `

recursive
lizard
Posts: 440
Joined: Oct 17, 2017 11:35
Location: Germany

### Re: Cow 15

Dodicat, your version is faster. And if the sub is called with calc 1,100000 it delivers the solution like mine: 150000.
srvaldez
Posts: 1893
Joined: Sep 25, 2005 21:54

### Re: Cow 15

I like your solution dodicat, I will now post the solution that was submitted to Dr. Mu translated from Mathematica to FB

Code: Select all

`'by Russ Coxfunction primaryq(byval n as longint) as integer   return iif(bit(n,0),-1,not primaryq(n\2))end functiondim as long count=1, primary=0while count<=50000   primary+=1   if primaryq(primary) then      count+=1   end ifwendprintprint "{ ";primary;" , ";2*primary;" } "`