I know that we can use the logic of binary adder where Sum = a XOR b and Carry = a AND b
I have also got a solution:
int add(int a, int b)
{
if(b == 0)
return sum;
sum = a ^ b;
carry = (a & b) << 1;
return add(sum,carry);
}
What I don't understand here is why is the carry bit shifted, or multiplied by 2 during each recursion?
I find this a bit tricky to explain, but here's an attempt; think bit by bit addition, there are only 4 cases;
0+0=0
0+1=1
1+0=1
1+1=0 (and generates carry)
The two lines handle different cases
sum = a ^ b
Handles case 0+1 and 1+0, sum will contain the simple case, all bit positions that add up to 1.
carry = (a & b) << 1
The (a & b) part finds all bit positions with the case 1+1. Since the addition results in 0, it's the carry that's important, and it's shifted to the next position to the left (<<1). The carry needs to be added to that position, so the algorithm runs again.
The algorithm repeats until there are no more carries, in which case sum will contain the correct result.
Btw, return sum should be return a, then both sum and carry could be regular local variables.
public class AddSub {
int sum=0,carry=0;
public static void main(String[] args) {
System.out.println("Add "+new AddSub().addition(93,5));
System.out.println("Sub "+new AddSub().subtraction(7,60));
System.out.println("Sub "+new AddSub().multiplication(9,60));
}
public int addition(int a, int b)
{
if(b==0)
{
return a;
}
else
{
sum = a^b;
carry = (a&b)<<1;
return addition(sum,carry);
}
}
public int subtraction(int a, int b){
return addition(a,addition(~b,1));
}
public int multiplication(int a, int b){
for(int i=0;i<b/2;i++)
sum = addition(sum,addition(a,a));
return sum;
}
}
Hi don't be think yourself too difficult.
Here the simple way to do that.
Consider a=5, b=10;
c=a-(-b);
c=15;
that is it.
Related
As mentioned here: gcd(a,b) = gcd(-a,b) = gcd(-a,-b). However when I use following code, I get different output for input being (-4,-8).
gcd(x,y) gives -4 wheras gcd(abs(x),abs(y)) gives 4.
Can some one help me understand where I am wrong.
int gcd(int a ,int b)
{
if(b==0)
return a;
return gcd(b,a%b);
}
int main()
{
int x,y;
cin>>x>>y;
cout<<gcd(x,y)<<endl; // gives -4
cout<<gcd(abs(x),abs(y))<<endl; //gives 4
return 0;
}
You're not taking into account that the output range has a plus or minus sign in it which breaks your algorithm, it's asserting that negative numbers and positive numbers are to be treated as the positive integers. Formal set theory in discrete mathematics has a different jargon set for symbols that are incompatible with most programming languages.
Greatest Common Denominator in C++ using recursion
int GCD(int A,int B)
{
if(A==0) return B;
if(B==0) return A;
A=abs(A);
B=abs(B);
if(A>B) return GCD(B,A);
return GCD(B%A,A);
}
Your algorithm cannot cover all positive and negative numbers. Use the code below.
int gcd(int a, int b){
a = abs(a);b = abs(b);
if (a == 0)
return b;
if (b == 0)
return a;
if (a == b)
return a;
if (a > b)
return gcd(a - b, b);
return gcd(a, b - a);
}
I think I am not calling the function or passing it correctly. Here are a couple of snippets that I am having issues with.
Using test data, 1/2 and 8/16 returns 1/2 instead of 1/1.
This is my code to calculate the GCD:
void Fractions::gcd(int n, int d)
{
int a,b,c;
a = n;
b = d;
while (a%b != 0)
{
c = a % b;
a = b;
b = c;
}
num = n/b;
denom = d/b;
}
This is the code that calculates will add numbers from input and calculate the GCD based from those numbers:
Fractions Fractions::operator+(Fractions& fraction2)
{
Fractions totalAddition;
totalAddition.num = (num * fraction2.denom + denom * fraction2.num);
totalAddition.denom = (denom * fraction2.denom);
totalAddition.gcd(num, denom); // i think issue is here
return totalAddition;
}
The only problem here is the name of the function.
A function called gcd should return the Greatest Common Divisor:
int gcd(int n, int d) {
int a, b, c;
a = n;
b = d;
while (a % b != 0) {
c = a % b;
a = b;
b = c;
}
return b;
}
It doesn't need to be a member function of Fraction to do this - it can be a standalone function, which is better, as it makes Fraction more encapsulated. But you can give it an overload which digests Fraction:
int gcd(const Fraction& frac){
return gcd(frac.numerator(), frac.denominator());
}
The name gcd is on the terse side but clear enough in context.
What your function is doing is it's simplifying a fraction, as a member function of a Fraction object, and overwriting that Fraction's member variables. So, it should be called simplify, and it doesn't need to take any input:
void Fractions::simplify() {
int a, b, c;
a = num;
b = denom;
while (a % b != 0) {
c = a % b;
a = b;
b = c;
}
num = n / b;
denom = d / b;
}
You might find you don't need a gcd function in which case simplify will be enough. But if you do need both functions, you can avoid some duplication of code here:
void Fractions::simplify() {
int g = gcd(*this);
num /= g;
denom /= g;
}
//Euclidean algorithm
//if b<a the gcd(a,b)=gcd(a-b,b)
int gcd(int a,int b)
{
while(a!=b)
{
if(a>b)
a=a-b;
else
b=b-a;
}
return a;
}
Output
15 12
3
//Optimal implementation of Euclidean Algorithm
int gcd(int a,int b)
{
if(b==0)
return a;
else
return gcd(b,a%b);
}
Output
15 12
3
I have a question about a function to determinate if a number is >, = or < than another.
If I have for example:
int fun(int a, int b)
{
if (a > b)
return a;
else
if (b > a)
return b;
else
return 0
}
(I don't want to use any cout that interacts with the user).
Now if I give 2 numbers it gives me a, b or 0. But for example if a put in the function a = -1 and b = 0, the function clearly returns 0 even if the 2 numbers are not equal.
Yes, I could check before calling the function if the 2 numbers are the same. Or I could use a variable to see in which case I am, for example:
int fun(int a, int b)
{
int k = 0;
if (a > b)
return k;
else
if (b > a)
return k+1;
else
return k+2
}
But all these solutions are not so elegant. Is there a way to distinguish a 0 int from another? Or in any case is there a method to be sure that a return value come from a given point in this case?
You don't need else when the statement inside the if returns. I would additionally return something with actual meaning, rather than just an int. For example:
enum Relationship { LessThan = -1, Equal, GreaterThan};
if(a==b)
return Relationship::Equal;
if(a>b)
return Relationship::GreaterThan;
return Relationship::LessThan;
In general, I probably wouldn't bother writing a fucntion like this because managing this trinary output seems more effort than it's worth, but I'm assuming this is some kind of exercise.
You can use pointers
int* fun(int *a, int *b)
{
if (*a > *b)
return a;
else
if (*b > *a)
return b;
else
return NULL
}
if return value isn't NULL you can give maximum number from returned value
I need to make a program that calculates the power of a given number using a recursive function. I wrote this I can't get it to work, once I get to the function itself it breaks. Any help? Thanks.
#include"stdafx.h"
#include<stdio.h>
#include<iostream>
using namespace std;
float power(float a, unsigned int b);
int main()
{
float a = 0;
unsigned int b = 0;
cout << "Insert base - ";
cin >> a;
cout << "Insert index - ";
cin >> b;
float result;
result = power(a, b);
cout << result;
return 0;
}
float power(float a, unsigned int b)
{
if (b <= 0)
{
return a;
}
return (a*power(a, b--));
}
Instead of b-- you need b-1 (or --b)
b-- reduces b by one, which has no effect because that instance of b is never used again. It passes the unreduced copy of b recursively.
Also, when b is zero, the result should be 1 rather than a
if ( b <= 0) return 1;
return a * power(a, --b);
But this question was asked so many times....
Recursion function to find power of number
Whenever we think about recursion, the first thing that comes to mind should be what the stopping criterion is. Next thing to consider is that we cannot have recursion without the use of a stack. Having said this, let us see at how we are able to implement this power function.
Stopping criteria
X ^ 0 = 1
Unwinding the stack
The base number may be raised to a positive or negative real number. Let us restrict our problem to just integers.
If A is the base and B the power, as a first step, take the absolute
value of B.
Secondly, store A in the stack and decrement B. Repeat
until B = 0 (stopping criterion). Store the result in the stack.
Thirdly, multiply all the A's stored by unwinding the stack.
Now the code
float power(float a, int b)
{
int bx = -b ? b < 0 : b;
if (bx == 0)
{
a = 1;
return a;
}
return 1/(a*power(a, --bx)) ? b < 0 : (a*power(a, --bx));
}
How cold I do the following:
say I have the number 10 and would like to append the number 317 to it. The resulting integer would be 10317. How can this be done. Also, once I have this number, how could I then for example remove the 17 off the end. Without using strings, and without obvious solving and adding.
Thanks
This will append both numbers
int append_a_and_b_as_int(int a, int b)
{
for(int tmp = b; tmp > 0; tmp % 10)
{
a *= 10;
}
return a + b;
}
This will get rid of the last n numbers
int remove_n_numbers_from_a(int n, int a)
{
for(int i = 0; i < n; i++)
{
a /= 10;
}
return a;
}
Appending :
int foo(int a, int b)
{
return a*pow(10, floor(log10(b))+1)+b;
}
Removing :
int bar(int a, int b)
{
return a/pow(10, floor(log10(b))+1);
}
For the first one:
int a = 10;
int b = 317;
int result = a * 1000 + b;
For the second:
int result2 = result / 100;
If this is something you need to do in your workplace I'd advise quitting.
You can treat your two numbers as numeric data and solve the question, or you can treat them as strings and use an append.