comp.lang.idl-pvwave archive
Messages from Usenet group comp.lang.idl-pvwave, compiled by Paulo Penteado

Home » Public Forums » archive » Re: Recursive Function Program in IDL
Show: Today's Messages :: Show Polls :: Message Navigator
E-mail to friend 
Return to the default flat view Create a new topic Submit Reply
Re: Recursive Function Program in IDL [message #46702 is a reply to message #46701] Wed, 14 December 2005 09:46 Go to previous messageGo to previous message
news.qwest.net is currently offline  news.qwest.net
Messages: 137
Registered: September 2005
Senior Member
"David Fanning" <davidf@dfanning.com> wrote in message
news:MPG.1e09eff8986d3ab0989ae7@news.frii.com...
> Folks,
>
> Does anyone have a handy recursive function that does something neat?
> Someone is asking, and I don't have time to work on this. He
> (apparently) can't get to the newsgroup.
>
> Thanks,
>
> David
>
> --
> David Fanning, Ph.D.
> Fanning Software Consulting, Inc.
> Coyote's Guide to IDL Programming: http://www.dfanning.com/


An old program in my hackware style of programming.
Honest, I program much better nowadays!!

This finds the prime factors of a number (i.e. for 9, it returns 3, 3).
Very useful for making sure you pass a factorable length time series to
an fft routine ( if time is important to you).

Cheers,
bob




; find the factors of a number

function factors, n,prevfactors=prevfactors


maxfactor = fix(sqrt(n))
if maxfactor le 1 then begin
if keyword_set(prevfactors) then begin
prevfactors = [prevfactors,n]
return,n
endif else begin
return,n
endelse
endif

fac = findgen(maxfactor-1)+2 ; 2 -- sqrt(n)

doloop = 1
factorflag = 0
counter = 0


while doloop do begin
if n mod fac(counter) eq 0 then begin
factorflag = 1
newfactor = fac(counter)
if keyword_set(prevfactors) then prevfactors = [prevfactors,newfactor] $
else prevfactors = newfactor
newnumber = n/newfactor
; to iterate is human, to recurse is divine
r = factors(newnumber,prevfactors=prevfactors)
doloop = 0
endif
counter = counter+1
if counter ge maxfactor-1 then doloop = 0
endwhile


if n_elements(prevfactors) eq 0 then prevfactors = n else begin
; only if n is prime do we add it here
if not(factorflag) then prevfactors = [prevfactors,n]
endelse




return,prevfactors


end


;;;;___________ test code here ___________________

n = 5001

r = factors(n)


print
print
print,'Finished calculating factors_______'
print,'Number: ',n
print,'Factors:'
print,r



end
[Message index]
 
Read Message
Read Message
Read Message
Read Message
Read Message
Previous Topic: Re: Fun Writing Books
Next Topic: Re: Polygon Clipping Algo in IDL

-=] Back to Top [=-
[ Syndicate this forum (XML) ] [ RSS ] [ PDF ]

Current Time: Sun Oct 12 09:46:34 PDT 2025

Total time taken to generate the page: 0.04622 seconds