我无法使用' /'和循环,我必须划分一些数字。 操作数是32位的,我不能使用递归。
我想过使用shr但它只给了我2 ^ n divison并且它也不会保存提醒。
任何想法?
答案 0 :(得分:1)
#include <stdio.h>
#include <stdlib.h>
int main()
{
div_t output;
output = div(27, 4);
printf("Quotient part of (27/ 4) = %d\n", output.quot);
printf("Remainder part of (27/4) = %d\n", output.rem);
output = div(27, 3);
printf("Quotient part of (27/ 3) = %d\n", output.quot);
printf("Remainder part of (27/3) = %d\n", output.rem);
return(0);
}
输出:
Quotient part of (27/ 4) = 6
Remainder part of (27/4) = 3
Quotient part of (27/ 3) = 9
Remainder part of (27/3) = 0
答案 1 :(得分:1)
根据幻数尝试此方法:
我是根据这个link实施的
只有固定除数才有用。
#include <iostream>
#include <cmath>
using namespace std;
int main() {
// your code goes here
unsigned long MAX_NUM=1<<30; //Max num = 1073741824
unsigned long num = 1073741824;
unsigned long divisor=17;
//unsigned long magic_num=round(double(MAX_NUM)/divisor);
unsigned long magic_num = 63161284 // Fixed for divisor = 17
unsigned long div = (num * magic_num) >> 30;
unsigned long remain = num - div * divisor;
cout << div << endl;
cout << remain << endl;
return 0;
}
答案 2 :(得分:0)
int a_div_b( int a, int b, int pow=0 ) {
if (a<b) return 0;
if (a < (b<<(pow+1)))
return a_div_b(a-(b<<pow), b) + (1<<pow);
return a_div_b(a, b, pow+1);
}
没有循环,没有/
,O((log(a/b))^2)
时间。我可能会提升到O(log(a/b))
,但我很懒(一旦找到它,就会从maximium pow中退出 down ,而不是备份)。
可以通过b-a_div_b(a,b)*a
轻松计算余数,而无需使用循环或/
。
它应该使用O(1)内存,因为它是尾端递归。
答案 3 :(得分:0)
如果这是一次学术练习,他们可能会要你这样做:
a / b :: == e **(log(a) - log(b))