-4

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?

Dorni
  • 699
  • 1
  • 5
  • 13

4 Answers4

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);
}

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
Fredrik Pihl
  • 44,604
  • 7
  • 83
  • 130
1

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;
}
Rama
  • 3,222
  • 2
  • 11
  • 26
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.

Paul R
  • 208,748
  • 37
  • 389
  • 560
Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
0

If this is an academic exercise, they are probably wanting you to do:

a/b ::== e**(log(a) - log(b))

user3344003
  • 20,574
  • 3
  • 26
  • 62
  • OP claims this is for a resource-constrained system, apparently, so transcendental functions are probably going to be off-limits, I imagine. – Paul R May 08 '17 at 18:27
  • 1
    And he want it with remainder. But I would rather close the question as unclear with such a requirements which do not align. – Eugene Sh. May 08 '17 at 18:27
  • 1
    it seems like we are getting into impossibility now here. – user3344003 May 08 '17 at 18:29