This is a common interview question (according to some interview sites) but I can find no normal answers on the Internet - some are wrong and some point to complex theory I expect not to be required in an interview (like the Bresenham algorithm).
The question is simple:
The circle equation is: x2 + y2 = R2. Given R, draw 0,0-centered circle as best as possible without using any floating point (no trig, square roots, and so on, only integers)
Graphing a circle anywhere on the coordinate plane is pretty easy when its equation appears in center-radius form. All you do is plot the center of the circle at (h, k), and then count out from the center r units in the four directions (up, down, left, right). Then, connect those four points with a nice, round circle.
If you can draw lines defined by two points , you can draw the representation of a circle on a canvas, knowing its center , and its radius . The approach is to determine a set of consecutive points located on the circumference, then join them with lines.
The methods used here vary from radius method, diameter method, 2P (two points) and 3P (three points) methods. The autoCAD users can apply various circle commands. 2P means drawing a circle on the basis of two points on the circumference. 3P means drawing a circle on the basis of three points on the circumference.
Bresenham-like algorithms are probably the expected answer, and can be derived without "complex theory". Start from a point (x,y)
on the circle: (R,0)
and maintain the value d=x^2+y^2-R^2
, initially 0. D is the squared distance from the current point to the circle. We increment Y, and decrement X as needed to keep D minimal:
// Discretize 1/8 circle:
x = R ; y = 0 ; d = 0
while x >= y
print (x,y)
// increment Y, D must be updated by (Y+1)^2 - Y^2 = 2*Y+1
d += (2*y+1) ; y++
// now if we decrement X, D will be updated by -2*X+1
// do it only if it keeps D closer to 0
if d >= 0
d += (-2*x+1) ; x--
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With