Sumar and the Floating Rocks

Famous wizard Sumar moonji kumaru is stuck in a huge room and has to save Hermione Granger from a monster. Kumaru is at location P1 given by integral coordinates (x1,y1) and Hermione is at location P2 given by integral coordinates (x2,y2). Sadly P1 and P2 are the only points at which floating rocks are present. The rest of the room is without a floor and underneath is hot lava.

Kumaru has to go from P1 to P2 but there are no floating rocks to walk on. Kumaru knows a spell that can make the rocks appear but only on the integral coordinates on the straight line joining P1 and P2.

How many rocks can appear at locations (x,y) on the line segment between P1 and P2 (excluding P1 and P2) which satisfy the condition that both x and y are integers?

Example:

Input: x1 = 2, y1 = 2, x2 = 5, y2 = 5
Output: 2

Approach

Java

public class FloatingRocks {
    public static void main(String[] args) {

        int x1 = 2, y1 = 2;
        int x2 = 5, y2 = 5;

        System.out.println(solve(x1, y1, x2, y2));

    }

    static int solve(int x1int y1int x2int y2) {
        return Math.abs(gcd(y1 - y2, x1 - x2)) - 1;
    }

    static int gcd(int iint j) {
        if (j == 0)
            return i;
        return gcd(j, i % j);
    }

}

C++

#include <bits/stdc++.h>
using namespace std;

int solve(int x1int y1int x2int y2)
{
    return abs(__gcd(y1 - y2x1 - x2)) - 1;
}

int main()
{

    int x1 = 2y1 = 2;
    int x2 = 5y2 = 5;

    cout << solve(x1y1x2y2<< "\n";

    return 0;
}


No comments:

Post a Comment