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. js控制treeview默认展开

    bootStrapTreeview 在bootstrap的treeview官网,可以找到这个方法,用js控制可以写成:$('#xxx').treeview('collapseNode',{silent ...

  2. JS-DOM-随时更新

    DOM里有三种节点:元素节点.文本节点和属性节点 getElmentById(); //id选择器  在JS中用此方法来查找获取  建议大小写 以免不兼容 有时候查找不到  DOM操作必须等到HTML ...

  3. AngularJs编辑器

    问题:在使用过程中遇到的问题就是:angularJS绑定不上值.后来找到一种可以用的方式. html页 <div class="all"> <script typ ...

  4. Linux系统调用和库函数

    #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unist ...

  5. 几种不同程序语言的HMM版本

    几种不同程序语言的HMM版本 “纸上得来终觉浅,绝知此事要躬行”,在继续翻译<HMM学习最佳范例>之前,这里先补充几个不同程序语言实现的HMM版本,主要参考了维基百科.读者有兴趣的话可以研 ...

  6. Java实现链式存储的二叉树

    二叉树的定义: 二叉树(BinaryTree)是n(n≥0)个结点的有限集,它或者是空集(n=0),或者由一个根结点及两棵互不相交的.分别称作这个根的左子树和右子树的二叉树组成. 二叉树的遍历方式主要 ...

  7. 前端开发必知必会:CSS Position 全解析

    此文根据Steven Bradley的<How Well Do You Understand CSS Positioning?>所译,整个译文带有我自己的理解与思想,如果译得不好或不对之处 ...

  8. C/C++程序员必备的15个编辑器和集成开发环境

    我们有许多的编程语言,像 Java,NET,PHP,Ruby,Perl 和 Python 等,但今天我们要讨论的是两个最古老和流行的语言的C和C++.它们都有其特殊的地方,更有效的功能和支持的工具,这 ...

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

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

  10. Tornado/Python 学习笔记(一)

    1.源代码下载及安装:http://www.tornadoweb.org/en/stable/ 2.python中xmlrpc库官方文档:https://docs.python.org/3/libra ...