I cannot use '/' and loops and I have to divide some numbers. operands are 32-bit and I can't use recursion.
I thought of using shr but it only gives me 2^n divison and it also won't save the reminder.
any Ideas?
I cannot use '/' and loops and I have to divide some numbers. operands are 32-bit and I can't use recursion.
I thought of using shr but it only gives me 2^n divison and it also won't save the reminder.
any Ideas?
#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);
}
Output:
Quotient part of (27/ 4) = 6
Remainder part of (27/4) = 3
Quotient part of (27/ 3) = 9
Remainder part of (27/3) = 0
Try this method based on magic numbers:
I implemented it based on this link
It is usefull only with fixed divisor.
#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;
}
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);
}
No loops, no /
, O((log(a/b))^2)
time. I could probably improve to O(log(a/b))
, but I am lazy (recurse down from maximium pow once you find it, not back up).
Remainder can be easily calculated via b-a_div_b(a,b)*a
without use of loops or /
.
It should use O(1) memory as it is tail-end-recursive.
If this is an academic exercise, they are probably wanting you to do:
a/b ::== e**(log(a) - log(b))