Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

พิมพ์ N บรรทัดของตัวเลข ที่ทุกคู่มี GCD เท่ากับ K

GCD

GCD ย่อมาจาก Greatest Common Divisor คือตัวหารร่วมมากของจำนวนเต็ม 2 จำนวนขึ้นไป ไม่นับ 0

ตัวอย่าง หา GCD ของ 48 และ 180

48 = 2 × 2 × 2 × 2 × 3
180 = 2 × 2 × 3 × 3 × 5
GCD = 2 × 2 × 3 = 12

ในโจทย์นี้ ต้องพิมพ์ N บรรทัด โดยแต่ละบรรทัดมีตัวเลขที่ GCD ระหว่างกันเป็นค่าที่กำหนด

Input: N=2 GCD=2
Output: 2-4-6-10
        14-16-18-22

อัลกอริทึม

START
Step 1 -> take input n (e.g. 2) and k (e.g. 2) as int values and i
Step 2 -> Loop For i to 0 and i < n and i++
    Print (k * (6 * i + 1))
    Print (k * (6 * i + 2))
    Print (k * (6 * i + 3))
    Print (k * (6 * i + 5))
    Print \n
Step 3 -> end loop
STOP

ตัวอย่างโค้ด (C)

#include <stdio.h>

int main() {
    int i, n = 2, k = 2;
    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("\n");
    }
    return 0;
}

ผลลัพธ์

2-4-6-10
14-16-18-22