簡體   English   中英

程序打印平方等於給定數字的所有數字組合

[英]Program to print all combinations of numbers whose square equal to given number

#include <stdio.h>

void printCombs(int n) {
    int i, j, limit = ceil(sqrt(n));
    for(i = 1; i < limit; i++) {
        for(j = i; j < limit; j++) {
            if(i*i + j*j == n) {
                printf("%d,%d\n", i, j);
                printf("%d,", j);
                printCombs(i*i);
                printf("\n%d,", i);
                printCombs(j*j);    
                printf("\n");
            }
        }
    }
}

int main() {

    int n;
    scanf("%d", &n);

    printCombs(n);

    return 0;
}

我寫了這段代碼,它輸出平方和等於給定輸入的數字組合。 代碼工作正常,但問題在於不需要的輸出。

例如我輸入 1000:

1000
10,30
30,6,8
8,
6,

10,18,24
24,
18,

18,26
26,
18,10,24
24,6,8
8,
6,

10,

首先我得到 10,30,這很好,因為 100+900 = 1000。

然后 30, 6, 8 => 900+36+64 = 1000。

然后 10、18、24 => 100 + 324 + 576 = 1000。

然后 18, 26 => 324 + 676 = 1000。

然后 18、10、24 => 576 + 100 + 324 = 1000。

現在這些都是組合。 但是正如您所看到的,屏幕上還有一些其他數字輸出,這是由於在遞歸調用之前的printf()不輸出任何內容。 最后當它輸出24, 6, 8 .` 時。 我無法弄清楚如何防止這種情況輸出。 我如何只打印這些組合? 感謝任何幫助。

與其一點一點地打印,不如嘗試在一個語句中打印所有數字。

為此,您可能需要稍微重寫一下您的函數。

這是我的嘗試

#include <math.h>
#include <stdio.h>

void printCombs2(int n, int k) {
    int limit = ceil(sqrt(n));
    for (int i = 1; i < limit; i++) {
        for (int j = i; j < limit; j++) {
            if (i*i + j*j == n) {
//                printf("%d, %d, %d\n", i, j, k);
                printf("%d, %d, %d ==> %d+%d+%d=%d\n", i, j, k, i*i, j*j, k*k, i*i+j*j+k*k);
            }
        }
    }
}

void printCombs(int n) {
    printf("combs(%d):\n", n);
    int limit = ceil(sqrt(n));
    for (int i = 1; i < limit; i++) {
        for (int j = i; j < limit; j++) {
            if (i*i + j*j == n) {
//                printf("%d, %d\n", i, j);
                printf("%d, %d ==> %d+%d=%d\n", i, j, i*i, j*j, i*i+j*j);
                printCombs2(i*i, j);
                printCombs2(j*j, i);
            }
        }
    }
    puts("");
}

int main(void) {
    printCombs(100);
    printCombs(1000);
    printCombs(10000);

    return 0;
}

查看它在 ideone.com 上運行

combs(100):
6, 8 ==> 36+64=100

combs(1000):
10, 30 ==> 100+900=1000
6, 8, 30 ==> 36+64+900=1000
18, 24, 10 ==> 324+576+100=1000
18, 26 ==> 324+676=1000
10, 24, 18 ==> 100+576+324=1000

combs(10000):
28, 96 ==> 784+9216=10000
60, 80 ==> 3600+6400=10000
36, 48, 80 ==> 1296+2304+6400=10000
48, 64, 60 ==> 2304+4096+3600=10000

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM