Skip to content

Instantly share code, notes, and snippets.

@taraijpn taraijpn/modcheck.c
Created Oct 23, 2017

Embed
What would you like to do?
剰余計算覚え書き(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);
}
}
@taraijpn

This comment has been minimized.

Copy link
Owner Author

commented Oct 23, 2017

DSPのために配列を使ったリングバッファの扱いを書き直しているときに罠に嵌ったのでメモ。いわゆる「負数の剰余」問題である。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.