Code Logo

Circle Area

Published at25 Jul 2026
Geometry Easy 0 views
Like0

Calculate the area of a circle given its radius r. The formula is A = π × r², where π (pi) is approximately 3.14159. The result should be a floating-point number.

For example, a circle with radius 1 has an area of π × 1² = π ≈ 3.14159. A circle with radius 5 has an area of π × 25 ≈ 78.54. If the radius is 0, the area is 0. The radius is always a non-negative integer.

This problem teaches you to work with geometric formulas and floating-point arithmetic. The area of a circle is one of the most fundamental formulas in geometry, appearing everywhere from engineering (pipe cross-sections) to astronomy (planetary disk area) to computer graphics (blur kernels).

Most programming languages provide pi as a constant: Math.PI in JavaScript/Java, math.pi in Python, pi() in PHP, and std::f64::consts::PI in Rust. Using the built-in constant ensures maximum precision. Alternatively, you can define pi manually as 3.141592653589793, but the built-in constant is preferred.

Accuracy matters when dealing with floating-point results. The judge compares expected and actual values with a tolerance of 1e-9, so minor floating-point rounding differences are acceptable. Avoid integer division pitfalls — ensure at least one operand in the multiplication is a float.

Example Input & Output

Example 1
Input
0
Output
0
Explanation

Zero radius

Example 2
Input
1
Output
3.141592653589793
Explanation

PI*1^2

Example 3
Input
10
Output
314.1592653589793
Explanation

PI*10^2

Example 4
Input
5
Output
78.53981633974483
Explanation

PI*5^2

Example 5
Input
2
Output
12.566370614359172
Explanation

PI*2^2

Algorithm Flow

Recommendation Algorithm Flow for Circle Area
Recommendation Algorithm Flow for Circle Area

Solution Approach

Multiply pi by the square of the radius using the language's built-in pi constant.

function solution(r) {
  return Math.PI * r * r;
}

The formula is A = πr², implemented as pi * r * r. In languages with operator precedence, r * r is computed first (the square), then multiplied by pi. For integer radius r, the multiplication promotes the result to a floating-point value automatically in most languages because pi is a float.

Using Math.PI (or equivalent) gives about 15-16 decimal digits of precision, which is more than enough for the 1e-9 tolerance used by the judge.

Time complexity is O(1), space complexity is O(1).

Best Answers

java
class Solution {
    public double solution(int r) {
        return Math.PI*r*r;
    }
}