euclid's extended algorithm C ++ - c++

I'm having an issue with Euclid's Extended Algorithm. (ax+by=gcd(a,b)) I'm trying to determine both the GCD and x and y. The GCD isn't a problem but using the loop method something is going wrong with x and y. Normally one number comes up as 0 and the other is an abnormally large negative number. Code follows:
#include <iostream>
using namespace std;
main ()
{
int a,b,q,x,lastx,y,lasty,temp,temp1,temp2,temp3;
cout << "Please input a" << endl;
cin >> a;
cout << "Please input b" << endl;
cin >> b;
if (b>a) {//we switch them
temp=a; a=b; b=temp;
}
//begin function
x=0;
y=1;
lastx=1;
lasty=0;
while (b!=0) {
q= a/b;
temp1= a%b;
a=b;
b=temp1;
temp2=x-q*x;
x=lastx-q*x;
lastx=temp2;
temp3=y-q*y;
y=lasty-q*y;
lasty=temp3;
}
cout << "gcd" << a << endl;
cout << "x=" << lastx << endl;
cout << "y=" << lasty << endl;
return 0;
}

Although the question has been asked a long time ago, but the answer will help someone who were finding C++ implementation of extended euclidean algorithm.
Here is a recursive C++ implementation:
int xGCD(int a, int b, int &x, int &y) {
if(b == 0) {
x = 1;
y = 0;
return a;
}
int x1, y1, gcd = xGCD(b, a % b, x1, y1);
x = y1;
y = x1 - (a / b) * y1;
return gcd;
}
Example with code:
#include <iostream>
int main()
{
int a = 99, b = 78, x, y, gcd;
if(a < b) std::swap(a, b);
gcd = xGCD(a, b, x, y);
std::cout << "GCD: " << gcd << ", x = " << x << ", y = " << y << std::endl;
return 0;
}
Input:
a = 99, b =78
Output:
GCD: 3, x = -11, y = 14

Two of your assignments are wrong they should be:
temp2 = x;
x=lastx-q*x;
lastx = temp2;
temp3 = y;
y = lasty-q*y;
lasty=temp3;
Example output with the above fixes:
Please input a
54
Please input b
24
gcd6
x=1
y=-2

Related

Quadratic equation solver outputting in unknown format

I'm trying to make a quadratic equation solver, but for some reason my program is giving me answers in an unknown format.
I entered the simple quadratic equation x^2 + 2x + 1 = 0, expecting my program to give x = -1 or x = -1, but instead it gave x = 0138151E or x = 0138152D. It looks like it outputs these values for x for any inputs (not recognizing unreal answers and catching them). Why is this and how can I fix it?
#include "../std_lib_facilities_revised.h"
class Imaginary {};
double square(int a)
{
return a * a;
}
double quadratic_solver_pos(int a, int b, int c)
{
double x = 0.0;
double radicand = square(b) - 4 * a * c;
if (radicand < 0) throw Imaginary{};
x = (-b + sqrt(radicand)) / (2 * a);
return x;
}
double quadratic_solver_neg(int a, int b, int c)
{
double x = 0.0;
double radicand = square(b) - 4 * a * c;
if (radicand < 0) throw Imaginary{};
x = (-b - sqrt(radicand)) / (2 * a);
return x;
}
int main()
try {
cout << "This program is a quadratic equation solver.\n";
cout << "Quadratic equations are of the form: ax^2 + bx + c = 0\n";
cout << "Enter a, b, and c, respectively:\n";
double a = 0;
double b = 0;
double c = 0;
cin >> a >> b >> c;
cout << "Your quadratic equation: " << a << "x^2 + " << b << "x + " << c << " = 0\n";
cout << "x = " << quadratic_solver_pos << " or x = " << quadratic_solver_neg << '\n';
}
catch (Imaginary) {
cout << "x is unreal\n";
}
You don't pass your variables to your functions.
You need to do it like so quadratic_solver_pos(a, b, c);.

Unable to get decimal output in c++ code.

#include <iostream>
#include <math.h>
using namespace std;
int sum (int x);
int factorial (int y);
int greatest (int p, int q, int r);
int percentage (int m1, int m2, int m3, int m4, int m5);
int formula (int r, int h);
int voter_age (int x);
int interest (int p, int r, int t);
void swap (int x, int y);
int tables (int i, int j, int k);
int distance (double x, double y, double z);
int speed (double x, double y, double z);
int power (double x, double y, double z);
int sqroot (double x, double y, double z);
int converter (double x, double y, double z);
int inr (double x, double y, double z);
int usd (double x, double y, double z);
int mtrs(double x, double y, double z);
int main () {
int a, b;
double x, y, p, q, m1, m2, m3, m4, m5, r, h, t, i, j, k, z, ans;
cout << "MAIN MENU";
cout << "\n 1. Sum of Natural nos.";
cout << "\n 2. Factorial";
cout << "\n 3. Greatest number among 3";
cout << "\n 4. Percentage(5 subjects)";
cout << "\n 5. Volume of cylinder";
cout << "\n 6. Vote age checker";
cout << "\n 7. interest_calculator";
cout << "\n 8. Swapping nos.";
cout << "\n 9. Table of a number.";
cout << "\n 10. Distance calculator";
cout << "\n 11. Speed calculator";
cout << "\n 12. Calculate the power of a number";
cout << "\n 13. Square root calculator";
cout << "\n 14. Converter";
cout <<
"\n \n Select one of the above option typing the serial number of the
same";
cin >> a;
switch (a) {
case 1:
cout << "Enter any number";
cin >> x;
ans = sum(x);
cout << ans;
break;
case 2:
cout << "Enter any number";
cin >> y;
ans = factorial(y);
cout << ans;
break;
case 3:
cout << "Enter 3 numbers";
cin >> p >> q >> r;
ans = greatest(p, q, r);
cout << ans << " is the biggest number";
break;
case 4:
cout << "Enter marks of 5 subjects ";
cin >> m1 >> m2 >> m3 >> m4 >> m5;
ans = percentage(m1, m2, m3, m4, m5);
cout << ans << "%";
break;
case 5:
cout << "enter value of radius" << "\n";
cin >> r;
cout << "Enter value of height" << "\n";
cin >> h;
ans = formula(r, h);
cout << ans;
break;
case 6:
cout << "Enter your age" << "\n";
cin >> x;
ans = voter_age(x);
break;
case 7:
cout << "Enter principle amount " << "\n";
cin >> p;
cout << "Enter rate " << "\n";
cin >> r;
cout << "Enter time " << "\n";
cin >> t;
ans = interest(p, r, t);
cout << ans;
break;
case 8:
cout << "Enter 1st number.";
cin >> x;
cout << "Enter 2nd number";
cin >> y;
break;
case 9:
cout << "Enter a number to display its table";
cin >> i;
ans = tables(i, j, k);
cout << ans;
break;
case 10:
cout << "Enter speed in km/hr" << endl;
cin >> x;
cout << "Enter time in hours" << endl;
cin >> y;
ans = distance(x, y, z);
cout << ans << "km";
break;
case 11:
cout << "Enter distance in km" << endl;
cin >> x;
cout << "Enter time in hours" << endl;
cin >> y;
ans = speed(x, y, z);
cout << ans << "km/hr.";
break;
case 12:
cout << "Enter a number" << endl;
cin >> x;
cout << "Enter the power" << endl;
cin >> y;
ans = power(x, y, z);
cout << ans;
break;
case 13:
cout << "Enter a number" << endl;
cin >> x;
ans = sqroot(x, y, z);
cout << ans;
break;
case 14:
cout << "Select one of the following" << endl;
cout << "\n a. Currency";
cout << "\n b. Distance";
cout << "\n c. mass";
cout << "\n d. temperature" << endl;
cin >> b;
switch (b) {
case 1:
cout << "Select one of the following:" << endl;
cout << "\t 1. For INR to USD type " << endl;
cout << "\t 2. For USD to INR type " << endl;
cin >> b;
switch (b) {
case 1:
cout << "Enter amount in INR" << endl;
cin >> y;
ans = inr(x, y, z);
cout << ans << "$";
break;
case 2:
cout << "Enter amount in USD" << endl;
cin >> y;
ans = usd(x, y, z);
cout << ans << "Rs.";
break;
}
break;
case 2:
cout << "Slect one of the following" << endl;
cout << "\t Mtrs to kms and cms" << endl;
cout << "\t Kms to Mtrs and cms" << endl;
cout << "\t Cms to Mtrs and Kms" << endl;
break;
case 3:
cout << "Select one of the following" << endl;
cout << "\t Kgs to grams and pounds" << endl;
cout << "\t Grams to Kgs and Pounds" << endl;
cout << "\t Pounds to kgs and grams" << endl;
break;
case 4:
cout << "Select one of the following" << endl;
cout << "\t Celcius to Farenhite and Kelvin" << endl;
cout << "\t Farenhite to Celcius and Kelvin" << endl;
cout << "\t Kelvin to Celcius and Farenhite" << endl;
break;
}
break;
default:
cout << "please enter correct option";
}
}
int sum (int x)
{
int i, sum = 0;
for (i = 1; i <= x; i++)
sum = sum + i;
return (sum);
}
int factorial (int y)
{
int i, fact = 1;
for (i = 1; i <= y; i++)
fact = fact * i;
return (fact);
}
int greatest (int p, int q, int r)
{
int s;
if ((p > q) && (p > r))
s = p;
else if ((q > p) && (q > r))
s = q;
else if ((r > p) && (r > q))
s = r;
return (s);
}
int percentage (int m1, int m2, int m3, int m4, int m5)
{
int s, q;
s = m1 + m2 + m3 + m4 + m5;
q = s / 5;
return (q);
}
int formula (int r, int h)
{
return (r * r * h * 3.14);
}
int voter_age (int x)
{
if (x >= 18)
cout << "eligible to vote";
else if (x < 18)
cout << "Not eligible to vote, wait for " << 18 - x << " years";
return (x);
}
int interest (int p, int r, int t)
{
return (p * r * t) / 100;
}
void swap (int x, int y)
{
x = x + y;
y = x - y;
x = x - y;
cout << "Value of x is " << x << "Value of y is " << y;
}
int tables (int i, int j, int k)
{
for (j = 1; j <= 10; j++)
{
k = i * j;
cout << i << "*" << j << "=" << k << "\n";
}
return (k);
}
int distance (double x, double y, double z)
{
z = x * y;
return (z);
}
int speed (double x, double y, double z)
{
z = x / y;
return (z);
}
int power (double x, double y, double z)
{
z = pow (x, y);
return (z);
}
int sqroot (double x, double y, double z)
{
z = sqrt (x);
return (z);
}
int inr (double x, double y, double z)
{
z = y * 69.70;
return (z);
}
int usd (double x, double y, double z)
{
z = (1 / 69.70) * y;
return (z);
}
int mtrs(double x, double y, double z)
{
z = (1/1000)*y;
return(z);
}
This code is my school project in which we were asked to create functions using switch. Everything is working fine except the outputs from converter(in the 1st switch case) or any other program which has to give decimal outputs.
On selecting converter from the menu, all the operations are programmed to get output in decimals but it is rounding off the numbers.
Be aware that integral types (char, unsigned int, (u)int<n>_t, size_t) all can only hold integral values. So if you assign them the value of some floating point type, you always lose the decimals.
Let's take distance as example:
int distance (double x, double y, double z)
{
z = x * y; // distance calculated as double!
return (z); // double is cast to int -> you lose the decimals
}
If you want to keep the decimals, return a floating point type:
double distance (double x, double y, double z);
// ^^
There are some other issues, though:
At first, don't use parentheses on return values!!! They have special meaning (creating a reference) and might give you unexpected results:
decltype auto distance (double x, double y, double z)
// ^ (!)
{
return (z);
}
Here, return type is deduced, and it will get a reference to the local variable z, so you end up in undefined behaviour!
Then why do you pass z as parameter at all? You don't ever use it, so make it a local variable instead:
double distance (double x, double y)
{
double z = x * y;
return z;
}
or even shorter, don't use an intermediate variable at all and return directly (prefer this style on short calculations):
return x * y;
Sometimes, you want to have additional output parameters, then you can pass these as parameters – but to be able to receive any value outside the function, you need to pass them as either reference or pointer. Prefer references if values always have to be provided, pointers only if nullptr is considered valid input as well.
int distance (double x, double y, double& z)
// ^ (!)
{
z = x * y;
return z;
}
// use:
double distance;
int rounded = distance(10.12, 12.10, distance);
In this example, you have two result values, the distance calculated (with decimals) in the double variable and the one with decimals cut away in the int variable. Be aware that there might be overflow when the double is converted to int!
Above is a rather bad example, as output is redundant, you'd do things like these if one of the outputs has different/independent meaning:
int distance (double x, double y, double& z)
{
// check input variables x and y
if(...)
{
return INVALID_PARAMETERS; // assuming you have an enum or a #define for
}
// calculations and other checks, different return values for different errors
z = x * y;
return SUCCESS;
}
This has a bit of C programming style, in C++, think of if throwing some exception possibly is more appropriate. An alternative approach to having output parameters is returning a struct or class – think of returning 2D or 3D coordinates in a struct 'Point' or complex results with real and imaginary part in a struct – well, guess – 'Complex' (be aware that there already is std::complex, though).
In addition to change return type from int to double...
Try to run with fixed and setprecision:
fixed to not remove extra 0 and setprecision to cut after some amount of decimal digits after decimal point.
for example:
#include <iomanip> //add this include
int main()
{
cout<< fixed;
double x = sum(3);
cout<<setprecision(5)<<x;
return 0;
}
/unspecified/ setprecision (int n);
Set decimal precision
Sets the decimal precision to be used to format floating-point values on output
operations.
Behaves as if member precision were called with n as argument on the
stream on which it is inserted/extracted as a manipulator (it can be
inserted/extracted on input streams or output streams).
This manipulator is declared in header <iomanip>.

Round very small numbers to zero (c++)

Is there any command in C++ to make,
1.354322e-23
into
0
This is my (simple) Program
#include "stdafx.h"
#include <iostream>
#include<iomanip>
int main()
{
float x;
std::cin >> x;
std::cout << x << std::endl;
return 0;
}
When I type values like,
2.2356e-17
It gives,
2.2356e-017
std::setprecision won't work either...
Edit:
OK this is my problem.
I created a program that can give sin cos and and tan values.
For cos 90, I want it to be 0 instead of -4.311e-008
Heres my real program
#include "stdafx.h"
#include <iostream>
#include<iomanip>
float Pi()
{
float pi = (atan(1) * 4);
return pi;
}
int Selector()
{
using namespace std;
cout << "Type:\t1 for Degrees\n\t2 for Radians\n\t3 for Gradians\n\nYour Choice : ";
int x;
cin >> x;
return x;
}
float D_R(float a)
{
float q = (a / 180);
float r = q*Pi();
return r;
}
float G_R(float a)
{
float q = (a / 200);
float r = q*Pi();
return r;
}
float All(float a, float o)
{
using namespace std;
std::cout << setprecision(5) << "sin(" << o << ") = " << sin(a) << std::endl;
std::cout << setprecision(5) << "cos(" << o << ") = " << cos(a) << std::endl;
std::cout << setprecision(5) << "tan(" << o << ") = " << tan(a) << std::endl;
return 0;
}
int main()
{
using namespace std;
int x = Selector();
cout << "Enter your angle : ";
float o;
cin >> o;
float d = D_R(o);
float g = G_R(o);
if (x == 1)
All(d, o);
else if (x == 2)
All(o, o);
else if (x == 3)
All(g, o);
return 0;
}
Edit:
Ok I came up with inserting
if (std::abs(sin(a)) < 0.0001) a = 0;
if (std::abs(cos(a)) < 0.0001) a = 0;
if (std::abs(tan(a)) < 0.0001) a = 0;
before my All() function
And that solved my problem
C++ can't arbitrarily round numbers down to 0 for you, it's up to you to define what a "very small number" is for your purposes.
Once you've determined the threshold, you simply need
if (std::abs(number) < THRESHOLD) number = 0;
RE: Your edits
For cos 90, I want it to be 0 instead of -4.311e-008
Again, it's up to you to define what the threshold is. Do you want 0.00000001 to be rounded to 0? What about 0.0001? What about 0.1? You need to define the line where rounding occurs.
Probably trunc() does what you want.
#include <cmath>
cout << roundf(2.2356e-17) << " " << trunc(2.2356e-17) << endl;
Output
0 0
See Also: round(), trunc(), nearbyint().

My c++ code for factoring isn't working

I am trying to create a c++ program that when I input two numbers (num1, combinationNum), it finds two numbers that multiply together to equal num1, but add together to equal combinationNum. It currently works for positive integers, but not negative. How do I make it work with negative integers? Also, If the equation isn't solvable, I would like it to print an error of some sort. Thanks!
Code:
//
// main.cpp
// Factor
//
// Created by Dani Smith on 2/13/14.
// Copyright (c) 2014 Dani Smith Productions. All rights reserved.
//
#include <iostream>
#include <cmath>
using namespace std;
void factors(int num, int comNum){
int a, b;
cout<<"The factors are ";
bool isPrime = true;
int root = (int)sqrt((double)num);
for(int i = 2; i <= root; i++){
if(num % i == 0 ){
isPrime = false;
//cout<<i<<",";
for(int x = 0; x<3; x++){
if(x==1){
a = i;
}
else if(x == 2){
b = i;
}
if(a + b == comNum){
cout << a << ", and " << b << ".";
}
}
}
}
//----------------------------------------
if(isPrime)cout<<"1 ";
cout<<endl;
}
int main(int argc, const char * argv[])
{
int num1 = 0, num2 = 0, multiple = 0, combinationNum = 0, output1 = 0, output2 = 0;
cout << "What number do you want to factor?\n";
cin >> num1;
cout << "What do you want them to add to?\n";
cin >> combinationNum;
factors(num1, combinationNum);
return 0;
}
To solve:
x + y == a
x * y == b
You have to solve
y == a - x
x * x - a * x + b == 0
So with delta == a * a - 4 * b, if delta positive, the solutions are
x1 = (a + sqrt(delta)) / 2
x2 = (a + sqrt(delta)) / 2
The code : (https://ideone.com/qwrSwa)
void solve(int sum, int mul)
{
std::cout << "solution for x + y = " << sum << std::endl
<< " x * y = " << mul << std::endl;
const int delta = sum * sum - 4 * mul;
if (delta < 0) {
std::cout << "No solution" << std::endl;
return;
}
const float sqrtdelta = sqrtf(delta);
const float x1 = (sum + sqrtdelta) / 2.f;
const float x2 = (sum - sqrtdelta) / 2.f;
std::cout << "x = " << x1 << ", y = " << sum - x1 << std::endl;
if (delta != 0) {
std::cout << "x = " << x2 << ", y = " << sum - x2 << std::endl;
}
}

How to simplify a fraction

I want to simplify a fraction in my application. The fraction is like,
x/y where x and y are integers.
I want to simplify the fraction to its simplest form.
Can anyone please give me hints how to do it.
Thanks in advance.
Compute the greatest common divisor for x and y
Divide both of them by the GCD
Euclid's algorithm is an easy way to compute the GCD.
Divide both by gcd(x,y)
The Binary GCD algorithm is a fast way to compute the GCD on a computer.
#include<iostream>
using namespace std;
struct fraction
{
int n1, d1, n2, d2, s1, s2;
};
void simplification(int a,int b)
{
bool e = true;
int t; int z;
for (int i = (a*b); i > 1;i--)
{ if ((a%i==0)&&(b%i==0))
{
t = a / i;
z = b / i;
}
else
{
e = false;
}
}
cout << "simplest form=" << t << "/" << z << endl;
}
void sum(int num1, int deno1, int num2, int deno2)
{
int k,y;
k = num1* deno2 + num2*deno1;
y = deno2*deno1;
cout << "addition of given fraction = " << k << "/" << y << endl;
simplification(k, y);
}
void sub(int num1, int deno1, int num2, int deno2)
{
int k, y;
k = num1*deno2 - num2*deno1;
y = deno1*deno2;
cout << "Substraction of given fraction = " << k << "/" << y << endl;
}
void mul(int num1, int deno1, int num2, int deno2)
{
int k, y;
k = num1*num2;
y = deno1*deno2;
cout << "multiplication of given fration= " << k<< "/" <<y; cout<< endl;
simplification(k, y);
}
void div(int num1, int deno1, int num2, int deno2)
{
int k, y;
;
k = num1*deno1;
y = deno1*num2;
cout << "division of given fraction" << k << "/" << y << endl;
simplification(k, y);
}
int main()
{ fraction a;
cout << "enter numirator of f1=";cin >> a.n1;
cout << "enter denominator of f1=";cin >> a.d1;
cout << "enter numirator of f2=";cin >> a.n2;
cout << "enter denominator of f2=";cin >> a.d2;
cout << "f1= " << a.n1 << "/" << a.d1 << endl;
cout << "f2= " << a.n2 << "/" << a.d2 << endl;
mul(a.n1, a.d1, a.n2, a.d2);
div(a.n1, a.d1, a.n2, a.d2);
sub(a.n1, a.d1, a.n2, a.d2);
sum(a.n1, a.d1, a.n2, a.d2);
system("pause");
}