마찬가지로 지수법은 반복 곱하기이므로 곱셈은 단순히 반복됩니다.
또 다른 기능 mulAetB
을 작성하면 부정 입력과 같은 것을주의해야합니다.
수준을 한 단계 더 높이고 증가분과 감소분으로 더하기를 정의 할 수 있지만 잔인 할 수 있습니다.
참조, 예를 들어, 부가의 과잉 방법을 사용하여 다음 프로그램 :
#include <stdio.h>
static unsigned int add (unsigned int a, unsigned int b) {
unsigned int result = a;
while (b-- != 0) result++;
return result;
}
static unsigned int mul (unsigned int a, unsigned int b) {
unsigned int result = 0;
while (b-- != 0) result = add (result, a);
return result;
}
static unsigned int pwr (unsigned int a, unsigned int b) {
unsigned int result = 1;
while (b-- != 0) result = mul (result, a);
return result;
}
int main (void) {
int test[] = {0,5, 1,9, 2,4, 3,5, 7,2, -1}, *ip = test;
while (*ip != -1) {
printf ("%d + %d = %3d\n" , *ip, *(ip+1), add (*ip, *(ip+1)));
printf ("%d x %d = %3d\n" , *ip, *(ip+1), mul (*ip, *(ip+1)));
printf ("%d^%d = %3d\n\n", *ip, *(ip+1), pwr (*ip, *(ip+1)));
ip += 2;
}
return 0;
}
이 프로그램의 출력을 표시하고 계산 올바른지 :
0 + 5 = 5
0 x 5 = 0
0^5 = 0
1 + 9 = 10
1 x 9 = 9
1^9 = 1
2 + 4 = 6
2 x 4 = 8
2^4 = 16
3 + 5 = 8
3 x 5 = 15
3^5 = 243
7 + 2 = 9
7 x 2 = 14
7^2 = 49
정말로 의 경우에 단일 기능이 있어야합니다. 함수 호출을 인라인으로 리팩터링하는 것은 간단합니다.
static unsigned int pwr (unsigned int a, unsigned int b) {
unsigned int xres, xa, result = 1;
// Catch common cases, simplifies rest of function (a>1, b>0)
if (b == 0) return 1;
if (a == 0) return 0;
if (a == 1) return 1;
// Do power as repeated multiplication.
result = a;
while (--b != 0) {
// Do multiplication as repeated addition.
xres = result;
xa = a;
while (--xa != 0)
result = result + xres;
}
return result;
}
이 사이트에서 본 최악의 타이틀 중 하나였습니다. 제목을 어떻게 다시 작성했는지 확인하십시오. –