Is it possible to predetermine variables x
and d
to call initialFunction()
without while(1)
loop?
void function( int xc, int yc, int r, int color ){
int x = 0;
int y = r;
int d = 1-2*r;
while( 1 ){
x++;
d += 4*x-2;
if( d>0 ){
initialFunction(x,y,d);
break;
}
}
while( x>=y ){
x++;
d += 4*x-2;
if( d>0 ){
// some code
}
}
}
>Solution :
Your loop is trying, in succession, cases with x=1
, x=2
, x=3
, ...
The 1st
time through, d
is 1-2r+(4 * 1-2)
The 2nd
time through, d
is 1-2r+(4 * 1-2) + (4 * 2-2)
…
The x
time through, d
is 1-2r+4*(sum from 1 to x)-2*x
With formula for triangle numbers this is d=1-2r+4*x*(x+1)/2-2x
which simplifies to d=1-2r+2x^2
Then d>0
implies 2x^2>2r-1
or x^2>r-1/2
.
So set x=ceil(sqrt(r-0.5))
and d=1-2r+2x^2