
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Number of Integral Points Between Two Points in C++
In this tutorial, we are going to write a program the finds the number of integral points between the given two points.
The number of points between two given points will be gcd(abs(x2), abs(y1-y2)) - 1.
If the line joining is parallel to x-axis, then the number of integral points will be abs(y1 - y2) - 1.
If the line joining is parallel to y-axis, then the number of integral points will be abs(x1 - x2) - 1
If the x points of both points are equal, then they are parallel to the x-axis. If the y points of both points are equal, then they are parallel to the y-axis.
Let's see an example.
Input
pointOne = [1, 5] pointTwo = [1, 3]
Output
1
Algorithm
- Initialise two points.
- Check whether they are parallel to x-axis or not.
- If they are parallel to the x-axis, then use the formula abs(y1 - y2) - 1.
- Check whether they are parallel to y-axis or not.
- If they are parallel to the y-axis, then use the formula abs(x1 - x2) - 1.
- If they are not parallel to any of the axes, then use the formula gcd(abs(x1-x2), abs(y1- y2)) - 1.
- Compute the result and print it.
Implementation
Following is the implementation of the above algorithm in C++
#include <bits/stdc++.h> using namespace std; int gcd(int a, int b) { if (b == 0) { return a; } return gcd(b, a % b); } int getCount(int pointOne[], int pointTwo[]) { if (pointOne[0] == pointTwo[0]) { return abs(pointOne[1] - pointTwo[1]) - 1; } if (pointOne[1] == pointTwo[1]) { return abs(pointOne[0] - pointTwo[0]) - 1; } return gcd(abs(pointOne[0] - pointTwo[0]), abs(pointOne[1] - pointTwo[1])) - 1; } int main() { int pointOne[] = {1, 3}, pointTwo[] = {10, 12}; cout << getCount(pointOne, pointTwo) << endl; return 0; }
Output
If you run the above code, then you will get the following result.
8
Advertisements