C++ or Python code and or Psudeo Code is acceptble. How would you make a functio
ID: 3541340 • Letter: C
Question
C++ or Python code and or Psudeo Code is acceptble.
How would you make a function for divison using no "*" or "/" operators?
One can say that you can simply do a recusion on the function
Divide(x,y):
if y == 1:
return x
if y == x:
return 1
if x <= y:
return 0
return Divide(x-y,y) + 1
But this way can be slow.
I belive the correct way to show this is to use Bitwise operators.
Please explain an algorthim for the bitwise rep or a diffrent way to speed the process.
Explanation / Answer
please rate - thanks
bitwise operations is not the answer.
if you wanted to divide by a power of 2, you could do it that way
I believe the solution you're looking for is repeated subtraction.
in addition recursion is slow, because of all the stack handling, that needs to be done
your sample code did integer division, so I did integer division for my solution
if need any changes, let me know
#include<iostream>
using namespace std;
int divide(int,int);
int main()
{cout<<divide(1,2)<<endl;
cout<<divide(5,6)<<endl;
cout<<divide(6,5)<<endl;
cout<<divide(15,3)<<endl;
system("pause");
return 0;
}
int divide(int a,int b)
{int ans=0;
while(a>=b)
{ans++;
a-=b;
}
return ans;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.