搜尋此網誌

2024年6月29日 星期六

用減法與位移做除法並取餘數

 #include <stdio.h>


unsigned int division_fun(unsigned int dividend, unsigned int divisor, unsigned int *remainder_ptr)
{
    unsigned int max_num, i, quotient;
    if ((dividend == 0) || (divisor == 0) || (dividend < divisor) || (remainder_ptr == NULL))
    {
        if ((dividend < divisor) && (remainder_ptr))
        {
            *remainder_ptr = dividend;
        }
        return 0;
    }

    for (max_num = 31; max_num > 0; max_num--)
    {
        if (dividend & (1 << max_num))
            break;
    }

    *remainder_ptr = dividend;
    quotient = 0;
    for (i = max_num; i > 0; i--)
    {
        if (*remainder_ptr >= (divisor << i))
        {
            *remainder_ptr -= (divisor << i);
            quotient |= (1 << i);
        }
    }

    if ((i == 0) && (*remainder_ptr >= (divisor << i)))
    {
        *remainder_ptr -= (divisor << i);
        quotient |= (1 << i);
    }

    return quotient;
}

int main()
{
    unsigned int var_a, var_b, quotient, remainder;

    printf("\nPlease input a and b values:");
    scanf("%d %d", &var_a, &var_b);

    printf("\n=============================================\n");
    quotient = division_fun(var_a, var_b, &remainder);
    printf("%d / %d = %d...%d", var_a, var_b, quotient, remainder);
    printf("\n=============================================\n");

    return 0;
}

Please input a and b values:123 3 ============================================= 123 / 3 = 41...0 =============================================

Please input a and b values:12345
132

=============================================
12345 / 132 = 93...69
=============================================

沒有留言:

張貼留言