Check if a Circle Lies Inside Another Circle or not in JavaScript

A circle is a closed curve where all points on the curve are equidistant from a fixed point called the center. In this problem, we are given the center points, and the radius values of two circles, we have to Check if a circle lies inside another circle or not using JavaScript.

Example:

Input:
center points of first circle: x1 = 2, y1 = 3, radius of first circle: r1 = 5
center points of first circle: x2 = 0, y2 = 0, radius of first circle: r1 = 10

Output: true

There are several approaches to check if a circle lies inside another circle or not in JavaScript which are as follows:

Table of Content

  • Distance Between Centers and Comparing Radii Approach
  • Comparing Radii and Centers Distance Approach

Distance Between Centers and Comparing Radii Approach

Define a JavaScript function that takes the coordinates (x1, y1) and radius r1 of the first circle, as well as the coordinates (x2, y2) and radius r2 of the second circle as its parameters. Use the distance formula to calculate the distance between the centers of the two circles. If the sum of the distance between the centers and the radius of the first circle is less than the radius of the second circle it return true else return false.

Example: Demonstration of Checking if a circle lies inside another circle or not using Distance Between Centers and Comparing Radii Approach.

JavaScript
function circleInsideCircle(x1, y1, r1, x2, y2, r2) {
    const distance = Math
        .sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2);
    return distance + r1 < r2;
}

// Coordinates and radius
//  of the first circle
const x1 = 2, y1 = 3, r1 = 5;
// Coordinates and radius
// of the second circle
const x2 = 0, y2 = 0, r2 = 10;
console.log(circleInsideCircle(x1, y1, r1, x2, y2, r2)); 

Output
true

Time complexity: O(1)

Space complexity: O(1)

Comparing Radii and Centers Distance Approach

Define a JavaScript function that takes the coordinates (x1, y1) and radius r1 of the first circle and coordinates (x2, y2) and radius r2 of the second circle as its parameters. Calculate the squared distance between the centers of the two circles. Check if the radius r1 of the inner circle is less than the difference between the radius r2 of the outer circle and the square root of the squared distance between their centers, then return true else return false.

Example: Demonstration of Checking if a circle lies inside another circle or not by Comparing Radii and Centers Distance Approach.

JavaScript
function circleInsideCircle(x1, y1, r1, x2, y2, r2) {
    const distanceSquared = (x2 - x1) ** 2 + (y2 - y1) ** 2;
    return r1 < r2 - Math
        .sqrt(distanceSquared);
}
// Coordinates and radius 
// of the first circle
const x1 = 2, y1 = 3, r1 = 5;
// Coordinates and radius
//  of the second circle
const x2 = 0, y2 = 0, r2 = 10;

console.log(circleInsideCircle(x1, y1, r1, x2, y2, r2)); 

Output
true

Time complexity: O(1)

Space complexity: O(1)