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

พิมพ์ n จำนวนแรกของลำดับ Newman-Conway

ลำดับ Newman-Conway ใช้สร้างลำดับจำนวนเต็มดังนี้

1 1 2 2 3 4 4 4 5 6 7 7 8 8 8 8 9 10 11 12

สูตรสำหรับสร้างลำดับ Newman-Conway สำหรับ n จำนวน คือ

P(n) = P(P(n - 1)) + P(n - P(n - 1)) โดยที่ P(1) = P(2) = 1

อัลกอริทึม

START
Step 1 -> Input variable n (e.g. 20)
Step 2 -> start variables as i, p[n+1], p[1]=1, p[2]=1
Step 3 -> Loop For i=3 and i<=n and i++
    Set p[i] = p[p[i - 1]] + p[i - p[i - 1]]
    Print p[i]
Step 4 -> End Loop For
STOP

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

#include <stdio.h>

int main() {
    int n = 20, i;
    int p[n + 1];
    p[1] = 1;
    p[2] = 1;
    printf("Newman-Conway Sequence is :");
    printf("%d %d ", p[1], p[2]);
    for (i = 3; i <= n; i++) {
        p[i] = p[p[i - 1]] + p[i - p[i - 1]];
        printf("%d ", p[i]);
    }
    return 0;
}

ผลลัพธ์

Newman-Conway Sequence is : 1 1 2 2 3 4 4 4 5 6 7 7 8 8 8 8 9 10 11 12