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
Related
https://github.com/mehedihasrifat
Please correct my mistake**
How can I solve this issue?
Did I do something wrong here?**
I have been trying to debug this code but ultimately I can't. Please help me, I'm totally new to this platform.
This picture shows the following code
/*
Written by Mehedi Hasan Rifat
Written on October 2, 2022
*/
#include <stdio.h>
int main()
{
int a, b, t, gcd, lcm;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
if (a == 0)
gcd = b;
else if (b == 0)
gcd = a;
else
{
while (b != 0)
{
t = b;
b = a % b;
a = t;
}
gcd = a;
}
lcm = (a * b) / gcd;
printf("LCM: %d\n", lcm);
return 0;
}
As jasonharper says in the comment, when you finished the gcd calculation, b will be always zero.
One quick fix is to add
int original_a = a;
int original_b = b;
and calculate lcm using:
lcm = (original_a * original_b) / gcd;
Or just use the __gcd() function in the <algorithm> library.
#include <algorithm>
int main()
{
...
lcm = (a * b) / std::__gcd(a, b);
}
I want to subtract two fractional numbers using operator overloading. I have write a piece of code in order to accomplish this task:
#include<iostream>
using namespace std;
void HCF(int& a, int& b)
{
int m, n;
m = a;
n = b;
while (m != n)
{
if (m > n)
m = m - n;
else
n = n - m;
}
a = a / m;
b = b / m;
}
class Rational {
int x1;
int y1;
public:
void simplify()
{
int m, n, r;
n = fabs(y1);
m = fabs(x1);
while (r = m % n)//Find the Maximum Common Number of m,n
{
m = n;
n = r;
}
y1 /= n; // Simplification
x1 /= n;
if (y1 < 0) // Convert denominator to positive number
{
y1 = -y1;
x1 = -x1;
}
}
Rational(int num = 0, int denom = 1)
{
if (denom) {
x1 = num;
y1 = denom;
}
else {
x1 = 0;
y1 = 1;
}
}
Rational(const Rational& copy)//Copy Constructor
{
x1 = copy.x1;
y1 = copy.y1;
}
Rational operator-(const Rational& x) const //Overloaded minus operator
{
Rational temp;
temp.x1 = x1 * x.y1 - x.x1 * y1;
temp.y1 = y1 * x.y1;
temp.simplify();
return temp;
}
operator string() const //Overloaded string operator
{
int numerator = x1, denominator = y1;
HCF(numerator, denominator);
string str;
if (denominator == 1)
str = to_string(numerator);
else
str = to_string(numerator) + "/" + to_string(denominator);
return str;
}
};
int main()
{
Rational a(5, 1);
Rational b(3, 4);
Rational c;
Rational d;
Rational x(5, 1);
c = a - x;
string expected1 = "0"; //Expected value
string actual1 = (string)c;//Actual value
cout << actual1.compare(expected1);//Comparing actual and expected value
d = c - b;
string expected2 = "-3/4";
string actual2 = (string)d;
cout << actual2.compare(expected2);
}
As we can see, in the main() function, both cout statements should print 0 because when we compare both strings, they must be equal. But the problem is, when I run this program, it prints nothing, and I don't know why.
My operator string() converts an integer fraction into a string. My operator- takes the LCM and finds the final value after subtracting two fractional numbers. In the main() function, I have declared five objects for class Rational, and then I simply perform subtraction and then I compare the expected and actual values, which should return 0 in the cout statement.
I have also used the simplify() member function to check whether the fraction is completely in simpler form or not. For example, it should simplify 2/4 into 1/2.
Where is the mistake? All other functions except operator- are running correctly. The real problem is with the operator-, ie when we perform c=a-x, the value of c would be 0 as a string. Similarly, if we perform d=c-b then the expected value should be -3/4 as a string.
I have also tried to run this code on Google Test, but it fails the test case.
Use this GCD (greatest common divisor) function to implement your HCF function. Yours currently exhibits an endless loop when given 0 as a first argument.
To reduce a fraction, divide numerator and denominator by their greatest common divisor.
This is called the Euclidean algorithm.
template <typename T>
T GCD(T a, T b) {
while (b != 0)
{
T t = a % b;
a = b;
b = t;
}
return std::max(a, -a);
}
Can someone correct this code please.
#include <iostream>
using namespace std;
int main()
{
int a;
int b;
int c;
double d;
double e;
double f;
double g;
f = a / b;
g = b / a;
c = 0;
cin >> a;
cin >> b;
f = a / b;
g = b / a;
if (a == b)
{
cout << a << endl;
return 0;
}
else if (f == int(f))
{
cout << a << endl;
return 0;
}
start:
while (a * b > c)
c = c + 1;
d = c / a;
e = c / b;
if (d == int(d))
if (e == int(e))
{
cout << c << endl;
return 0;
}
else if (d != int(d))
goto start;
else if (e != int(e))
goto start;
if (a * b <= c)
cout << a * b << endl;
}
No matter what the
else if(f==int(f))
code is always executed. Eg. I put in 3 and 5 and even though 3/5 gives a decimal the else if is always executed and outputs 3. WHAT AM I MISSING HERE?
The primary error in your code leading to the problem with the if statement is the integer division. You have to cast the operands to doubles to perform floating point division:
cin >> a;
cin >> b;
f = double(a) / double(b);
g = double(b) / double(a);
There are other issues to clean up, but this is the one that leads to your question.
These expression, though they are assigning to double variables, calculate integer divisions.
f = a / b;
g = b / a;
d = c / a;
e = c / b;
I.e. what gets assigned to the doubles are integer values.
Your if-conditions basically check for integer values and hence always evaluate to true.
In order to avoid the integer division and get actual floating point values assigned to the doubles, you need to make sure early that the compiler interprets them accordingly. E.g.:
f = (1.0*a) / b;
g = (1.0*b) / a;
d = (1.0*c) / a;
e = (1.0*c) / b;
And, as a comment points out, better always init all your variables (even if here a,b,c would be enough).
int a=1;
int b=1;
int c01;
double d=1.0;
double e=1.0;
double f=1.0;
double g=1.0;
You just need to define type a and b as double not int.
I want to compute the sum of two fraction using lcm of numerator and denominator. That means as a result I want to get a fraction in the reduced form. I have the following cpp file.
#include <iostream> //need it for cin and cout
#include "fraction.h"
Fraction::Fraction()
{
num = 1;
den = 1;
}
Fraction::Fraction(int n, int d)
{
int tmp_gcd = gcd(n, d);
num = n / tmp_gcd;
den = d / tmp_gcd;
}
int Fraction::gcd(int a, int b)
{
int tmp_gcd = 1;
// Implement GCD of two numbers;
return tmp_gcd;
}
int Fraction::lcm(int a, int b)
{
return a * b / gcd(a, b);
}
Fraction operator+(const Fraction&a,const Fraction &b)
{
int c=(lcm(b.den,a.den)/b.den)*a.num+b.num*(lcm(b.den,a.den)/a.den);
int d=lcm(b.den,a.den);
Fraction result(c,d);
return result;
}
However this code does not work because lcm is not defined in this scope.
What is the key that allows lcm work in this scope? If you please could explain more, I would be very thankful.
lcm is a member of Fraction. You can refer to it just as lcm within members of Fraction; but operator+ isn't a member, so you'll have to use the qualified name Fraction::lcm.
It will also need to be static. (Hopefully it already is, but I can't see the declaration to be sure).
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.