Skip to content

Instantly share code, notes, and snippets.

@chizuchizu
Last active November 21, 2021 05:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chizuchizu/f377b50e09241ee6de23aa6398fc3721 to your computer and use it in GitHub Desktop.
Save chizuchizu/f377b50e09241ee6de23aa6398fc3721 to your computer and use it in GitHub Desktop.
#include <stdio.h>
int AND(int a, int b) {
return a * b;
}
int OR(int a, int b) {
return (a + b + 1) / 2;
}
int NOT(int a) {
return 1 - a;
}
int XOR(int a, int b) {
return AND(NOT(AND(a, b)), OR(a, b));
}
int FA0(int a, int b, int c) {
return XOR(XOR(a, b), c);
}
int FA1(int a, int b, int c) {
int res = 0;
res = OR(AND(a, b), res);
res = OR(AND(b, c), res);
res = OR(AND(a, c), res);
return res;
}
int main() {
// 入力は非負整数
int INP1, INP2;
char operator;
scanf("%d %c %d", &INP1, &operator, &INP2);
int carry;
switch (operator) {
case '+':
carry = 0;
break;
case '-' :
carry = 1;
break;
default:
printf("+ か - の演算が使えます。");
return 0;
}
// bit列は余裕を持って
int BIT1[100], BIT2[100];
int length_bit = 1;
// bit長をはかる log_2 {num}を愚直にやっている
int max_num = 2;
while (INP1 >= max_num || INP2 >= max_num) {
max_num *= 2;
// printf("%d ", max_num);
length_bit++;
}
length_bit++;
int res1, res2;
res1 = INP1;
res2 = INP2;
BIT1[length_bit] = 0;
BIT2[length_bit] = carry;
printf("length_bit %d \n", length_bit);
printf("INPUT BIT\n");
// 10進数の入力から2進数に変換する
// 左が1の桁になっていることに注意
int pow_2 = 1; // 2^0
for (int i = 0; i < length_bit; i++) pow_2 *= 2; // 2^(n - 1)
if (BIT2[length_bit] == 1) {
res2 = pow_2 - INP2;
BIT2[length_bit] = 1;
carry = 0;
}
pow_2 /= 2;
for (int i = length_bit - 1; i >= 0; i--) {
if (res1 / pow_2 == 1) {
res1 -= pow_2;
BIT1[i] = 1;
} else {
BIT1[i] = 0;
}
if (res2 / pow_2 == 1) {
res2 -= pow_2;
BIT2[i] = 1;
} else {
BIT2[i] = 0;
}
pow_2 /= 2;
}
// 表示部分
printf("INPUT 1: ");
for (int i = length_bit; i >= 0; i--) {
printf("%d ", BIT1[i]);
}
printf("\nINPUT 2: ");
for (int i = length_bit; i >= 0; i--) {
printf("%d ", BIT2[i]);
}
// 表示部分終わり
int ANS[100];
printf("\n");
// 任意bitの加算
for (int i = 0; i <= length_bit; i++) {
// printf("%d %d %d | %d %d\n", BIT1[i], BIT2[i], carry, FA1(BIT1[i], BIT2[i], carry), ANS[i]);
ANS[i] = FA0(BIT1[i], BIT2[i], carry);
carry = FA1(BIT1[i], BIT2[i], carry);
}
// ANS[length_bit + 1] = carry;
printf("\n");
printf("ANS BIT: ");
for (int i = length_bit; i >= 0; i--) {
printf("%d ", ANS[i]);
}
int ans_10 = 0;
pow_2 = 1;
// 2進数から10進数に変換
for (int i = 0; i < length_bit; i++) {
// printf("%d", ANS[i]);
ans_10 += ANS[i] * pow_2;
pow_2 *= 2;
}
ans_10 -= pow_2 * ANS[length_bit];
printf("\n%d %c %d = %d\n", INP1, operator, INP2, ans_10);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment