Cow 15

General discussion for topics related to the FreeBASIC project or its community.
Post Reply
srvaldez
Posts: 3379
Joined: Sep 25, 2005 21:54

Cow 15

Post by srvaldez »

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

Post by lizard »

This?

Code: Select all

' cow.bas

dim as short used(100000)

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

Re: Cow 15

Post by lizard »

Or this?

Code: Select all

' cow2.bas

dim shared as short used(1000000)

dim as integer i,e

do
  i += 1
  if not used(i) then 
    print i, i*2, 
    used(i*2) = -1
    e += 1
  endif
loop until e = 100000

print:print
print "100000th =" ,i 
Last edited by lizard on Feb 02, 2018 20:10, edited 1 time in total.
srvaldez
Posts: 3379
Joined: Sep 25, 2005 21:54

Re: Cow 15

Post by srvaldez »

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=1

while 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+=1
wend 
lizard
Posts: 440
Joined: Oct 17, 2017 11:35
Location: Germany

Re: Cow 15

Post by lizard »

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

Re: Cow 15

Post by srvaldez »

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

Post by lizard »

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

Re: Cow 15

Post by dodicat »

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 sub

calc 1,100
sleep
  
recursive
lizard
Posts: 440
Joined: Oct 17, 2017 11:35
Location: Germany

Re: Cow 15

Post by lizard »

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

Re: Cow 15

Post by srvaldez »

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 Cox
function primaryq(byval n as longint) as integer
	return iif(bit(n,0),-1,not primaryq(n\2))
end function

dim as long count=1, primary=0
while count<=50000
	primary+=1
	if primaryq(primary) then
		count+=1
	end if
wend
print

print "{ ";primary;" , ";2*primary;" } "
Post Reply