簡體   English   中英

如何在 C 中找到兩個給定數字的公共質因數?

[英]How to find common prime factors of two given numbers in C?

我正在嘗試解決這個問題:

輸入:第一行包含一個 integer T ,它代表您需要解決的案例總數。 每個測試用例包含PQ ,以空格分隔,代表您需要處理的數字。

Output:打印PQ的最小因子和最大素因子相乘的結果。

約束條件: 1 ≤ ≤ 1002 ≤, ≤ 1000000

樣本輸入: 2 210 84 6 12
樣本 Output:

Case #1: 14 
Case #2: 6 

說明:讓我們以第一種情況為例。 數字210和84有幾個相同的質因數,分別是2、3、7。數字“2”是這兩個數字的最小公質因數,而“7”是他們最大的公質因數。 所以,結果一定是 2 和 7 的乘積,即 14。

這是我一直在使用的代碼,我試圖從給定的數字中找到因子,將因子存儲到數組中,然后檢查素數,但我覺得這不是正確的算法:(

void factor(int num1) {
    int arrA[100000], a = 0, flag = 1;
    //check factor
    for (int i = 2; i <= num1; i++) {
        if (num1 % i == 0) {
            arrA[a] = i;
            a++;
        }
    }
    // check prime
    for (int i = 0; i < a; i++) {
        for (int j = 2; j < a; j++) {
            if ((arrA[i] % j) == 0) {
                flag = 0;
            }
        }
        if (flag == 1) {
            printf("%d ", arrA[i]);
        }
        flag = 1;
    }
    printf("\n");
}

您的 function 無法正確計算質因數,因為它會找到非質因數。 對於num = 6 ,它將找到23以及6

當您發現i除以num時,您應該將num除以i ,否則增加i

然后,您可以使arrA小得多,因為int中素數的最大數量小於int中的位數: 31位對於 32 位整數和63位對於 64 位整數就足夠了。

一旦你有了num的質因數,你應該嘗試找到除以另一個數字的最小和最大。 請注意,第一個和最后一個這樣的質數可能相同,如果這些數沒有共同的質因數,則它們甚至可能不存在。

請注意,您不需要存儲因數:對於num的每個質因數,您可以嘗試檢查它是否能整除另一個數,並保留第一個整除的和最后一個整除的。

這是一個簡單的實現:

#include <stdio.h>

int main() {
    int i, n, a, aa, b, p, p1, p2;

    if (scanf("%d", &n) == 1) {
        for (i = 1; i <= n; i++) {
            if (scanf("%d%d", &a, &b) != 2)
                break;
            p1 = p2 = 1;
            aa = a;
            for (p = 2; p * p <= aa; p++) {
                if (aa % p == 0) {
                    /* p is a prime factor of a */
                    if (b % p == 0) {
                        /* p is a common prime factor */
                        p2 = p;
                        if (p1 == 1) {
                            /* p is the smallest common prime factor */
                            p1 = p;
                        }
                    }
                    /* remove p as a factor of aa */
                    do { aa /= p; } while (aa % p == 0);
                }
            }
            if (aa > 1) {
                /* aa is the largest prime factor of a */
                if (b % aa == 0) {
                    /* aa is the largest common prime factor */
                    p2 = aa;
                    if (p1 == 1) {
                        /* aa is also the smallest common prime factor */
                        p1 = aa;
                    }
                }
            }
            /* print the product of the smallest and largest common prime factors */
            /* if a == b and a is a large prime, a * a might overflow int */
            printf("Case #%d: %lld\n", i, (long long)p1 * p2);
        }
    }
    return 0;
}

暫無
暫無

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

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