Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Print N lines of numbers such that every pair among numbers has a GCD K
In C programming, we can print N lines of numbers where every pair among the numbers has a specific GCD (Greatest Common Divisor). This involves generating sequences of numbers that maintain the required GCD property.
What is GCD?
GCD stands for Greatest Common Divisor of two or more integers (excluding 0). It is the largest positive integer that divides all the given numbers without remainder.
For example, to find the GCD of 48 and 180 −
- 48 = 2 × 2 × 2 × 2 × 3
- 180 = 2 × 2 × 3 × 3 × 5
The greatest common divisor = 2 × 2 × 3 = 12.
Problem Statement
We need to print N lines where each line contains numbers such that the GCD of any pair of numbers from all lines equals the specified value K.
Input: N=2, K=2 Output: 2-4-6-10 14-16-18-22
Algorithm
The algorithm generates numbers using the formula K * (6 * i + offset) where offset values are chosen to ensure the GCD property −
START Step 1 ? Take input n (number of lines) and k (required GCD) Step 2 ? Loop for i from 0 to n-1 Print k * (6 * i + 1) Print k * (6 * i + 2) Print k * (6 * i + 3) Print k * (6 * i + 5) Print newline Step 3 ? End loop STOP
Example
Here's the complete C program to print N lines with the required GCD property −
#include <stdio.h>
int main() {
int i, n = 2, k = 2;
printf("Printing %d lines with GCD = %d:<br>", n, k);
for (i = 0; i < n; i++) {
printf("%d-", (k * (6 * i + 1)));
printf("%d-", (k * (6 * i + 2)));
printf("%d-", (k * (6 * i + 3)));
printf("%d", (k * (6 * i + 5)));
printf("<br>");
}
return 0;
}
Printing 2 lines with GCD = 2: 2-4-6-10 14-16-18-22
How It Works
The formula ensures that all generated numbers are multiples of K, guaranteeing that their GCD will be at least K. The specific offsets (1, 2, 3, 5) are chosen such that the GCD of all numbers across all lines remains exactly K.
Key Points
- All generated numbers are multiples of the required GCD value K
- The formula
k * (6 * i + offset)ensures proper distribution - Offsets 1, 2, 3, 5 maintain the GCD property across all lines
Conclusion
This approach efficiently generates N lines of numbers with a specified GCD using a mathematical formula. The method ensures all pairs maintain the required GCD property while producing distinct sequences for each line.
