/* Ajith - Syntax Higlighter - End ----------------------------------------------- */

3.13.2013

Divide a number by 3 without using any arithmetic operators

How to divide a number by 3 without using operators + - / * %

NOTE: I am just trying to collect various answers down in this post available across multiple sites in internet as mentioned in references.

Solution 01:
#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE *fp=fopen("temp.dat","w+b");
    int number=12346;
    int divisor=3;
    char *buf = calloc(number,1);
    fwrite(buf,number,1,fp);
    rewind(fp);
    int result=fread(buf,divisor,number,fp);
    printf("%d / %d = %d", number, divisor, result);
    free(buf);
    fclose(fp);
    return 0;
}

Above solution is a bit tricky so let us simplify it
  1. Open a temporary file i.e. temp.dat in write mode.
  2. Allocate a temporary "buf" of size "number".
  3. Now fwrite writes "number" of bytes from "buf" into FILE STREAM "fp". (In the above code since the value of "number" variable is 12346, we write 12346 bytes from "buf" into "temp.dat" file). 
  4. rewind will reset the file pointer "fp" to the start of the file. 
  5. fread reads "number" of elements of data, each "divisor" bytes long, from FILE STREAM "fp" and writes into "buf". Hence the return value of fread is 4115 in the above example. If you write 30 bytes and read back from the file in units of 3 then fread returns 10 which equivalent to 30 / 3.

Solution 02: 
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    int num = 1234567;
    int den = 3;
    div_t r = div(num,den); // div() is a standard C function.
    printf("%dn", r.quot);

    return 0;
}

Solution 03:
#include <stdio.h>
#include <stdlib.h>

int add(int x, int y) {
  int a, b;
  do {
    a = x & y;
    b = x ^ y;
    x = a << 1;
    y = b;
  } while (a);
  return b;
}

int divideby3 (int num) {
  int sum = 0;
  while (num > 3) {
    sum = add(num >> 2, sum);
    num = add(num >> 2, num & 3);
  }
  if (num == 3)
    sum = add(sum, 1);
  return sum;   
}

int main()
{
  int number=30;

  printf("%d n", divideby3(number));
  return 0;
}
References: 
  1. Stackoverflow.

No comments :

Post a Comment

Your comments are moderated