搜尋此網誌

2024年6月28日 星期五

最小公因數函式遞迴方式

 #include <stdio.h>


unsigned int least_common_factor(unsigned int var_a, unsigned int var_b)
{
    unsigned int i, total;
    total = 1;
    if ((var_a > 1) && (var_b > 1))
    {
        for (i = 2; i <= ((var_a < var_b) ? var_a : var_b); i++)
        {
            if (((var_a % i) == 0) && ((var_b % i) == 0))
            {
                total *= least_common_factor(var_a / i, var_b / i) * i;
                break;
            }
        }
    }

    return total; // least common factor
}

int main()
{
    unsigned int var_a;
    unsigned int var_b;

    printf("\nPlease input two value:");
    scanf("%d %d", &var_a, &var_b);

    printf("\n=============================================\n");
    printf("a = %d, b = %d, and least_common_factor is %d", var_a, var_b, least_common_factor(var_a, var_b));
    printf(", and greatest common multiple is %d", var_a * var_b / least_common_factor(var_a, var_b));
    printf("\n=============================================\n");

    return 0;
}

Please input two value:25 35 ============================================= a = 25, b = 35, and least_common_factor is 5, and greatest common multiple is 175 =============================================

Please input two value:34 68

=============================================
a = 34, b = 68, and least_common_factor is 34, and greatest common multiple is 68
=============================================

沒有留言:

張貼留言