Divide a number by 3 without using *, /, +, -, % operators

原帖: http://stackoverflow.com/questions/11694546/divide-a-number-by-3-without-using-operators

===============================================================================================================================

This question has been asked in an Oracle interview.

How would you divide a number by 3 without using */+-%, operators?

The number may be signed or unsigned.

===============================================================================================================================

There is a simple function I found here. but it's using the + operator, so you have to add the values with the bit-operators:

// replaces the + operator
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; 
}

As Jim commented this works because:

  • n = 4 * a + b
  • n / 3 = a + (a + b) / 3
  • So sum += an = a + b, and iterate.
  • When a == 0 (n < 4)sum += floor(n / 3); i.e. 1if n == 3, else 0

===============================================================================================================================

Idiotic conditions call for an idiotic solution:

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

If also the decimal part is needed, just declare result as double and add to it the result offmod(number,divisor).

Explanation of how it works

  1. The fwrite writes number bytes (number being 123456 in the example above).
  2. rewind resets the file pointer to the front of the file.
  3. fread reads a maximum of number "records" that are divisor in length from the file, and returns the number of elements it read.

If you write 30 bytes then read back the file in units of 3, you get 10 "units". 30 / 3 = 10

===============================================================================================================================

log(pow(exp(number),0.33333333333333333333)) /* :-) */

===============================================================================================================================

Using cloud computing :D

Google Search: 30 divided by 3

// 这个太威武了! 哈哈......

===============================================================================================================================

#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("%d\n", r.quot);

    return 0;
}

===============================================================================================================================

Use inline assembler: (also works for negative numbers now)

#include <stdio.h>

int main() {
  int dividend = -42, divisor = 3, quotient, remainder;

  __asm__ ( "movl   %2, %%edx;"
            "sarl  $31, %%edx;"
            "movl   %2, %%eax;"
            "movl   %3, %%ebx;"
            "idivl      %%ebx;"
          : "=a" (quotient), "=d" (remainder)
          : "g"  (dividend), "g"  (divisor)
          : "ebx" );

  printf("%i / %i = %i, remainder: %i\n", dividend, divisor, quotient, remainder);
}

===============================================================================================================================

Use itoa to convert to base 3 string. Drop last trit and convert back to base 10.

// Note: itoa is non-standard but actual implementations
// don't seem to handle negative when base != 10
int div3(int i) {
  char str[42];
  sprintf(str, "%d", INT_MIN); // put minus sign at str[0]
  if (i>0) str[0] = ' ';       // remove sign if positive
  itoa(abs(i), &str[1], 3);    // put ternary absolute value starting at str[1]
  str[strlen(&str[1])] = '\0'; // drop last digit
  return strtol(str, NULL, 3); // read back result
}

===============================================================================================================================

The request says "a number", not "any number", so:

  1. Check if the number is 3.
  2. If so, return 1.
  3. If not, report an invalid input.

Job done, but for extra marks, you could implement a dictionary of commonly requested multiples of three.

===============================================================================================================================

(note: see Edit 2 below for a better version!)

This is not as tricky as it sounds, because you said "without using the [..] + [..] operators". See below, if you want to forbid using the + character all together.

unsigned div_by(unsigned const x, unsigned const by) {
  unsigned floor = 0;
  for (unsigned cmp = 0, r = 0; cmp <= x;) {
    for (unsigned i = 0; i < by; i++)
      cmp++; // that's not the + operator!
    floor = r;
    r++; // neither is this.
  }
  return floor;
}

then just say div_by(100,3) to divide 100 by 3.


Edit: You can go on and replace the ++ operator as well:

unsigned inc(unsigned x) {
  for (unsigned mask = 1; mask; mask <<= 1) {
    if (mask & x)
      x &= ~mask;
    else
      return x & mask;
  }
  return 0; // overflow (note that both x and mask are 0 here)
}

Edit 2: Slightly faster version without using any operator that contains the +,-,*,/,% characters.

unsigned add(char const zero[], unsigned const x, unsigned const y) {
  // this exploits that &foo[bar] == foo+bar if foo is of type char*
  return (int)(uintptr_t)(&((&zero[x])[y]));
}

unsigned div_by(unsigned const x, unsigned const by) {
  unsigned floor = 0;
  for (unsigned cmp = 0, r = 0; cmp <= x;) {
    cmp = add(0,cmp,by);
    floor = r;
    r = add(0,r,1);
  }
  return floor;
}

We use the first argument of the add function because we cannot denote the type of pointers without using the* character, except in function parameter lists, where the syntax type[] is identical to type* const.

FWIW, you can easily implement a multiplication function using a similar trick to use the 0x55555556 trick proposed by AndreyT:

int mul(int const x, int const y) {
  return sizeof(struct {
    char const ignore[y];
  }[x]);
}

===============================================================================================================================



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
毕设新项目-基于Java开发的智慧养老院信息管理系统源码+数据库(含vue前端源码).zip 【备注】 1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用!有问题请及时沟通交流。 2、适用人群:计算机相关专业(如计科、信息安全、数据科学与大数据技术、人工智能、通信、物联网、自动化、电子信息等)在校学生、专业老师或者企业员工下载使用。 3、用途:项目具有较高的学习借鉴价值,不仅适用于小白学习入门进阶。也可作为毕设项目、课程设计、大作业、初期项目立项演示等。 4、如果基础还行,或热爱钻研,亦可在此项目代码基础上进行修改添加,实现其他不同功能。 欢迎下载!欢迎交流学习!不清楚的可以私信问我! 毕设新项目-基于Java开发的智慧养老院信息管理系统源码+数据库(含vue前端源码).zip毕设新项目-基于Java开发的智慧养老院信息管理系统源码+数据库(含vue前端源码).zip毕设新项目-基于Java开发的智慧养老院信息管理系统源码+数据库(含vue前端源码).zip毕设新项目-基于Java开发的智慧养老院信息管理系统源码+数据库(含vue前端源码).zip毕设新项目-基于Java开发的智慧养老院信息管理系统源码+数据库(含vue前端源码).zip毕设新项目-基于Java开发的智慧养老院信息管理系统源码+数据库(含vue前端源码).zip毕设新项目-基于Java开发的智慧养老院信息管理系统源码+数据库(含vue前端源码).zip毕设新项目-基于Java开发的智慧养老院信息管理系统源码+数据库(含vue前端源码).zip毕设新项目-基于Java开发的智慧养老院信息管理系统源码+数据库(含vue前端源码).zip
综合小区管理系统管理系统按照操作主体分为管理员和用户。管理员的功能包括报修管理、车位管理、车位分配管理、出入管理、字典管理、房屋管理、物业费缴纳管理、公告管理、物业人员投诉管理、我的私信管理、物业人员管理、用户管理、管理员管理。用户的功能包括管理部门以及部门岗位信息,管理招聘信息,培训信息,薪资信息等。该系统采用了Mysql数据库,Java语言,Spring Boot框架等技术进行编程实现。 综合小区管理系统管理系统可以提高综合小区管理系统信息管理问题的解决效率,优化综合小区管理系统信息处理流程,保证综合小区管理系统信息数据的安全,它是一个非常可靠,非常安全的应用程序。 管理员权限操作的功能包括管理公告,管理综合小区管理系统信息,包括出入管理,报修管理,报修管理,物业费缴纳等,可以管理操作员。 出入管理界面,管理员在出入管理界面中可以对界面中显示,可以对招聘信息的招聘状态进行查看,可以添加新的招聘信息等。报修管理界面,管理员在报修管理界面中查看奖罚种类信息,奖罚描述信息,新增奖惩信息等。车位管理界面,管理员在车位管理界面中新增。公告管理界面,管理员在公告管理界面查看公告的工作状态,可以对公告的数据进行导出,可以添加新公告的信息,可以编辑公告信息,删除公告信息。
void SOSC_init_8MHz(void) { SCG->SOSCDIV = 0x00000101; /* SOSCDIV1 & SOSCDIV2 =1: divide by 1 */ SCG->SOSCCFG = 0x00000024; /* Range=2: Medium freq (SOSC between 1MHz-8MHz)*/ // SCG->SOSCCFG = 0x00000034; /* Range=3: High freq (SOSC between 8MHz-40MHz)*/ /* HGO=0: Config xtal osc for low power */ /* EREFS=1: Input is external XTAL */ while(SCG->SOSCCSR & SCG_SOSCCSR_LK_MASK); /* Ensure SOSCCSR unlocked */ SCG->SOSCCSR = 0x00000001; /* LK=0: SOSCCSR can be written */ /* SOSCCMRE=0: OSC CLK monitor IRQ if enabled */ /* SOSCCM=0: OSC CLK monitor disabled */ /* SOSCERCLKEN=0: Sys OSC 3V ERCLK output clk disabled */ /* SOSCLPEN=0: Sys OSC disabled in VLP modes */ /* SOSCSTEN=0: Sys OSC disabled in Stop modes */ /* SOSCEN=1: Enable oscillator */ while(!(SCG->SOSCCSR & SCG_SOSCCSR_SOSCVLD_MASK)); /* Wait for sys OSC clk valid */ } void SPLL_init_160MHz(void) { while(SCG->SPLLCSR & SCG_SPLLCSR_LK_MASK); /* Ensure SPLLCSR unlocked */ SCG->SPLLCSR = 0x00000000; /* SPLLEN=0: SPLL is disabled (default) */ SCG->SPLLDIV = 0x00000302; /* SPLLDIV1 divide by 2; SPLLDIV2 divide by 4 */ SCG->SPLLCFG = 0x00180000; /* PREDIV=0: Divide SOSC_CLK by 0+1=1 */ /* MULT=24: Multiply sys pll by 4+24=40 */ /* SPLL_CLK = 8MHz / 1 * 40 / 2 = 160 MHz */ while(SCG->SPLLCSR & SCG_SPLLCSR_LK_MASK); /* Ensure SPLLCSR unlocked */ SCG->SPLLCSR = 0x00000001; /* LK=0: SPLLCSR can be written */ /* SPLLCMRE=0: SPLL CLK monitor IRQ if enabled */ /* SPLLCM=0: SPLL CLK monitor disabled */ /* SPLLSTEN=0: SPLL disabled in Stop modes */ /* SPLLEN=1: Enable SPLL */ while(!(SCG->SPLLCSR & SCG_SPLLCSR_SPLLVLD_MASK)); /* Wait for SPLL valid */ }
07-14
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值