Java 检查两个给定的圆是否相切或相交(Check if two given circles touch or intersect each other)

有两个圆 A 和 B,圆心分别为C1(x1, y1)和C2(x2, y2),半径分别为R1和R2。任务是检查圆 A 和 B 是否相互接触。

例如:  

输入: C1 = (3, 4) 
        C2 = (14, 18) 
        R1 = 5, R2 = 8
输出:圆圈互相不接触。

输入: C1 = (2, 3) 
        C2 = (15, 28) 
        R1 = 12, R2 = 10
输出:圆圈相互相交。

输入: C1 = (-10,8)
        C2 = (14,-24)
        R1 = 30,R2 = 10

方法:

中心 C1 和 C2 之间的距离计算如下

 C1C2 = sqrt((x1 - x2) 2 + (y1 - y2) 2 )。

有三种情况会出现。

    1、如果C1C2 <= R1 – R2:圆 B 位于 A 内。

    2、如果C1C2 <= R2 – R1:圆 A 位于 B 内。

    3、如果C1C2 < R1 + R2:圆互相相交。

    4、如果C1C2 == R1 + R2:圆 A 和 B 相互接触。

    5、否则,圆 A 和圆 B 不重叠

下面是上述方法的实现:

// Java program to check if two
// circles touch each other or not.
import java.io.*;

class GFG {
    static void circle(int x1, int y1, int x2, int y2,
                       int r1, int r2)
    {
        double d = Math.sqrt((x1 - x2) * (x1 - x2)
                             + (y1 - y2) * (y1 - y2));

        if (d <= r1 - r2) {
            System.out.println("Circle B is inside A");
        }
        else if (d <= r2 - r1) {
            System.out.println("Circle A is inside B");
        }
        else if (d < r1 + r2) {
            System.out.println("Circle intersect"
                               + " to each other");
        }
        else if (d == r1 + r2) {
            System.out.println("Circle touch to"
                               + " each other");
        }
        else {
            System.out.println("Circle not touch"
                               + " to each other");
        }
    }

    // Driver code
    public static void main(String[] args)
    {
        int x1 = -10, y1 = 8;
        int x2 = 14, y2 = -24;
        int r1 = 30, r2 = 10;
        circle(x1, y1, x2, y2, r1, r2);
    }
}

// This article is contributed by vt_m.

输出:

Circle touch to each other(圆互相触碰)

时间复杂度: O(log(n)),因为使用内置 sqrt 函数 

辅助空间: O(1)

如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

csdn_aspnet

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值