This is an interesting question from one of the lab assignments in Introduction to Computer Systems, fall 2018 at Peking University.

Problem Description

Given a 32-bit integer \(x\)(in two's complement), implement a C function that returns \(\frac{x}{6}​\) using ONLY bit manipulations(operators like ~ ! | ^ & << >> +). Your function should behave exactly as the C expression x/6.

Hint: You can use the following formula(Formula 1)

\[2 = \frac{2+1}{2} \times \frac{2^2+1}{2^2} \times \frac{2^4+1}{2^4}\times\frac{2^8+1}{2^8}...
\]

Inspiration

Since division is very slow using hardware, compilers often use optimizations to speed up division. For example, gcc will replace x/6 with x*171/1024 when x is relatively small, and implement x*171/1024 with shift left and shift right instructions. However, our function must cover all 32-bit two's complement integers, which means some other techniques are needed to make such replacement possible.

Resolution

We can change Formula 1 into the following form:

\[\frac{1}{6} = \frac{1}{8} \times \frac{2^2+1}{2^2} \times \frac{2^4+1}{2^4}\times\frac{2^8+1}{2^8}...
\]

Thus we can calculate this(Formula 2)

\[p = \frac{x}{8} \times \frac{2^2+1}{2^2} \times \frac{2^4+1}{2^4}\times\frac{2^8+1}{2^8} \times \frac{2^{16}+1}{2^{16}}
\]

Which can be implmented using a combination of shift-right and add operations(note that you must program carefully to avoid overflows). However, errors occur since expressions like x>>y return \(\lfloor x/2^y \rfloor\). We can counter the error by this(Formula 3)

\[\frac{x}{6} = p + \frac{x}{6} - p = p + \frac{1}{6}(x-6p)
\]

Since errors introduced by shift-rights will only cause \(p\) to be smaller than \(\frac{x}{6}\), we can deduce that \(x-6p > 0\). You can then approximate an upper bound of \(x-6p\), which depends on your implementation of Formula 2.

Suppose that \(x-6p < M\)(where M is small), then we can approximate \(\frac{1}{6}\) in Formula 3 using some \(X \approx \frac{1}{6}\) while keeping the equation true

\[\lfloor \frac{1}{6} (x-6p)\rfloor = \lfloor X \cdot (x-6p) \rfloor
\]

Choose a proper \(X = a/2^b\), and we are done!

/*
* divSix - calculate x / 6 without using /
* Example: divSix(6) = 1,
* divSix(2147483647) = 357913941,
* Legal ops: ~ ! | ^ & << >> +
* Max ops: 40
* Rating: 4
*/
int divSix(int x) {
int p;
int q,y,t;
x=x+(x>>31&5);
p=x>>3;
p=p+(p>>2);
p=p+(p>>4);
p=p+(p>>8);
p=p+(p>>16);
q=~p+1;
t=x+(q<<1)+(q<<2);
t=t+(t<<1)+(t<<3);
return p+(t>>6);
}

Implementing x / 6 Using Only Bit Manipulations的更多相关文章

  1. java.lang.IncompatibleClassChangeError: Implementing class的解决办法,折腾了一天总算解决了

    一,问题产生背景 git更新代码重启服务器后,问题就莫名奇妙的产生了,一看报错信息,基本看不懂,然后上百度去查,基本都是说jar包冲突,于是把矛头指向maven 二,问题的解决过程 既然确定了是mav ...

  2. Implementing Navigation with UINavigationController

    Implementing Navigation with UINavigationController Problem You would like to allow your users to mo ...

  3. Implementing SQL Server Row and Cell Level Security

    Problem I have SQL Server databases with top secret, secret and unclassified data.  How can we estab ...

  4. ios警告:Category is implementing a method which will also be implemented by its primary class 引发的相关处理

    今天在处理项目中相关警告的时候发现了很多问题,包括各种第三方库中的警告,以及各种乱七八糟的问题  先说说标题中的问题  Category is implementing a method which ...

  5. Hadoop on Mac with IntelliJ IDEA - 3 解决MRUnit - No applicable class implementing Serialization问题

    本文讲述在IntelliJ IDEA中使用MRUnit 1.0.0测试Mapper派生类时因MapDriver.withInput(final K1 key, final V1 val)的key参数被 ...

  6. Implementing the skip list data structure in java --reference

    reference:http://www.mathcs.emory.edu/~cheung/Courses/323/Syllabus/Map/skip-list-impl.html The link ...

  7. The JSR-133 Cookbook for Compiler Writers(an unofficial guide to implementing the new JMM)

    The JSR-133 Cookbook for Compiler Writers by Doug Lea, with help from members of the JMM mailing lis ...

  8. RH253读书笔记(6)-Lab 6 Implementing Web(HTTP) Services

    Lab 6 Implementing Web(HTTP) Services Goal: To implement a Web(HTTP) server with a virtual host and ...

  9. Implementing HTTPS Everywhere in ASP.Net MVC application.

    Implementing HTTPS Everywhere in ASP.Net MVC application. HTTPS everywhere is a common theme of the ...

随机推荐

  1. Vue 插槽详解

    Vue插槽,是学习vue中必不可少的一节,当初刚接触vue的时候,对这些掌握的一知半解,特别是作用域插槽一直没明白. 后面越来越发现插槽的好用. 分享一下插槽的一些知识吧. 分一下几点: 1.插槽内可 ...

  2. ACM选修HUST1058(市赛题) Lucky Sequence 同余定理

    Description Edward  得到了一个长度为  N  的整数序列,他想找出这里面有多少个“幸运的”连续子序列.一个连续子序列被称为“幸运的”,当且仅当该子序列内的整数之和恰好是  K  的 ...

  3. 重构改善既有代码设计--重构手法08:Replace Method with Method Object (以函数对象取代函数)

    你有一个大型函数,其中对局部变量的使用,使你无法釆用 Extract Method. 将这个函数放进一个单独对象中,如此一来局部变量就成了对象内的值域(field) 然后你可以在同一个对象中将这个大型 ...

  4. git使用(1)----推送代码到远程

    git使用(1) 首先要明白git上有三个区域 1.工作区 2.暂存区 3.历史记录区 步骤: 1.git  init 2.配置环境(如果配置一次了以后就不用再继续配置) git  config  - ...

  5. 《HTML5编程之旅》系列三:WebSockets 技术解析

    本文主要研究HTML5 WebSockets的使用方法,它是HTML5中最强大的通信功能,定义了一个全双工的通信信道,只需Web上的一个Socket即可进行通信,能减少不必要的网络流量并降低网络延迟. ...

  6. 【BZOJ】2120: 数颜色 带修改的莫队算法

    [题意]给定n个数字,m次操作,每次询问区间不同数字的个数,或修改某个位置的数字.n,m<=10^4,ai<=10^6. [算法]带修改的莫队算法 [题解]对于询问(x,y,t),其中t是 ...

  7. 【洛谷 P2512】 [HAOI2008]糖果传递(贪心)

    题目链接 环形均分纸牌. 设平均数为\(ave\),\(g[i]=a[i]-ave\),\(s[i]=\sum_{j=1}^ig[i]\). 设\(s\)的中位数为\(s[k]\),则答案为\(\su ...

  8. 常见的bug

    常见bug 一. Android系统功能测试设计的测试用例: a.对所测APP划分模块 b.详细列出每个模块的功能点(使用Xmind绘制功能图) c.使用等价类划分.边界值.场景法等对各功能点编写测试 ...

  9. 如何将vmworkstation的虚机导成ovf模版

    如何将vmworkstation的虚机导成ovf模版 最近碰见一个事情挺烦的苦恼了我好长一段时间,是这样的公司要进行攻防演练需要搭建一个owaps的靶站练手,环境我在我的电脑上已经搭好了(vmwork ...

  10. supervisor之启动rabbitmq报错原因

    前言 今天重启了服务器,发现supervisor管理的rabbitmq的进程居然启动失败了,查看日志发现老是报错,记录一下解决的办法. 报错:erlexec:HOME must be set 找了网上 ...