-3

I need to make a C++ calculator that can +, -, *, /, % and ^. I cannot use +, -, *, /, and % in my code at all.

#include<iostream>
using namespace std;
typedef long long ll;
ll add(ll a,ll b){ 
    if(b==0)return a;
    else return add(a^b,(a&b)<<1);
}
ll sub(ll a,ll b){ 
    if(b==0)return a;
    else return sub(a^b,((~a)&b)<<1);
}

Here is what I have. I don't know how to code the multiplication and division parts. Any help?

  • looks like homework, please review the question rules and try to ask an specific problem rather asking help for a general issue. – Kayvan Tehrani Dec 25 '17 at 05:55
  • A simple google search results in many questions like this, e.g. https://stackoverflow.com/questions/5284898/implement-division-with-bit-wise-operator – pepperjack Dec 25 '17 at 05:55
  • Please don't use macros like `ll`. – PaulMcKenzie Dec 25 '17 at 06:11
  • May I know why? –  Dec 25 '17 at 06:12
  • 4
    First, macros are to be used sparingly. Second, why obfuscate something as obvious as `long long`? Third, `ll` looks like `11`. Fourth, the code becomes harder to understand. Fifth, you want to get a job as a programmer? – PaulMcKenzie Dec 25 '17 at 06:13
  • Wow that seems harsh! HAHA. Anyways Im i kid, and I dont think I would mistake it for 11. –  Dec 25 '17 at 10:01
  • Re: "harsh" -- yes, a bit, but that's a bad habit to get into. If you do it now you'll have to unlearn it later. – Pete Becker Dec 25 '17 at 14:06

1 Answers1

0
ll mul(ll a,ll b){ 
    if(b<0){
        b=add(~b,1);
        a=add(~a,1);
    }
    ll res=0;
    while(b>0){
        if(b&1)res=add(res,a);
        a<<=1;
        b>>=1;
    }
    return res;
}
ll div(ll a,ll b){
    ll c=0,op=0;
    if(a<0){
        a=add(~a,1);
        op^=1;
    }
    if(b<0){
        b=add(~b,1);
        op^=1;
    }
    if(b!=0){
        while(a>=b){
            a=sub(a,b);
            c=add(c,1);
        }
    }
    if(op)c=add(~c,1);
    return c;
}

Following your code format, I hope this solution helps! Here, I make use of the add and subtract to do the multiply and divide, using more bitwise operators ( &, |, ^, ~, <<, >> ) . You could also refer to cplusplus.com to read more about them. So in this case you can see then in multiplication, I shift the bits to the left, so it is sort of like moving the ones place to the tens place, etc. If you need further clarifications, feel free to seek help. :)

QuIcKmAtHs
  • 297
  • 4
  • 18
  • Recommend a bit of care in how you answer homework and homework-esque questions. Homework answers should be light on code and heavy on explanation because if you simply hand off a ball of code, all the asker is likely to get from it is slightly improved skill at cutting and pasting. The end result is often [Cargo Cult Programming](https://en.wikipedia.org/wiki/Cargo_cult_programming), and no one benefits from that. [Except maybe Cthulhu](https://en.wikipedia.org/wiki/Cthulhu). – user4581301 Dec 25 '17 at 06:35