taraijpn
10/23/2017 - 7:44 PM

剰余計算覚え書き(C言語)

剰余計算覚え書き(C言語)

#include<stdio.h>
#include<stdlib.h>

int main()
{
        int a[4] = {3, -3, 3, -3};
        int b[4] = {8, 8, -8, -8};
        int i = 0;
        div_t r, rx;

        printf("a%%b \n");
        for (i = 0; i < 4; i++)
                printf(" %2d %% %2d = %2d \n", a[i], b[i], a[i] % b[i]);

        printf("(a+b)%%b \n");
        for (i = 0; i < 4; i++)
                printf(" %2d %% %2d = %2d \n", a[i], b[i], (a[i] + b[i]) % b[i]);

        printf("a&(b-1) \n");
        for (i = 0; i < 4; i++)
                printf(" %2d & (%2d-1) = %2d \n", a[i], b[i], a[i] & (b[i] - 1));

        printf("(a%%b+b)%%b \n");
        for (i = 0; i < 4; i++)
                printf(" %2d %% %2d = %2d \n", a[i], b[i], (a[i] % b[i] + b[i]) % b[i]);

        printf("r=div(a,b), r.quot, r.rem \n");
        for (i = 0; i < 4; i++) {
                r = div(a[i], b[i]);
                printf(" %2d %% %2d = %2d ... %2d \n", a[i], b[i], r.quot, r.rem);
        }

        printf("r=div(a,b), rx=div(r.rem+b, b) , rx.quot, rx.rem\n");
        for (i = 0; i < 4; i++) {
                r = div(a[i], b[i]);
                rx = div(r.rem + b[i], b[i]);
                printf(" %2d %% %2d = %2d ... %2d \n", a[i], b[i], rx.quot, rx.rem);
        }

}