📜  C++程序不使用*,/,+,-,%运算符将数字除以3

📅  最后修改于: 2021-05-06 19:54:25             🧑  作者: Mango

对于给定的正数,我们需要将数字除以3,而不使用任何这些*,/,+,-%运算符

例子:

Input : 48 
Output : 16

Input : 16  
Output : 5 

算法

  1. 取一个数字num,sum = 0
  2. while(num> 3),将数字左移两位,并且sum = add(num >> 2,sum)。创建一个函数add(x,y)以按位运算符将两个数相加
    • 取x,y
    • 运行do while循环,直到a不为零
    • a = x&y,b = x ^ y ;, y = b;
    • 在终止循环返回值b之后,得出x和y的和
  3. 取num与3的按位与
    对于新的num = add(num >> 2,num&3)
  4. 在终止while循环后,打印得出最终结果的和值。
// C++ program for divided a number by
// 3 without using operator
#include 
using namespace std;
  
// A function to add 2 numbers without using +
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;
}
  
// Function to divide by 3
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;
}
  
// Driver program
int main(void)
{
    int num = 48;
    cout << "The number divided by 3 is ";
    cout << divideby3(num);
  
    return 0;
}
输出:
The number divided by 3 is 16