[R] function stays in loop

Jim Lemon jim at bitwrit.com.au
Mon Dec 3 04:43:59 CET 2012


On 12/02/2012 10:57 PM, Mkkl wrote:
> function<- function(p){
> i<- 2
> r<- 0
> while(i<  p) {
> 	q<- (p/i)
> 		while(q>=1) {
> 			q=(q-1)
> }
> 		if (q==0) {
> 			r=1
> } 		else
> 			i=i+1
> }
> return(r)
> }
>
> This function stays in some kind of loop when I enter 4 as a function value.
> It immediately returns 0 when I inter 3 though.
> I don't seem te get why it does not give me just a result. Can someone tell
> me why it stays in a loop?
>
Hi Michiel,
Elementary really. You have programmed a Rube Goldberg test for whether 
a number is even or odd. If it returns, the number is odd, if it gets 
into an infinite loop. Play around with the initial value of i for more fun.

Jim




More information about the R-help mailing list