Greatest Common Divisor using Euclidian Algorithm? - c++

So I'm having a problem with my code here.
I am coding a Greatest Common Divisor using the Euclidian Algorithm and I can't seem to utilize the loop in order to keep the division to keep repeating until I get the greatest common divisor. So for now, I am able to get the remainder but do not know how to go on from there basically.
Any help will be greatly appreciated!
Here is what I have so far
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int a;//Holds the first number
int b;//Holds the second number
int temp;//Assign to greatest number
int hold;//Assign to smaller number
float euclid;//soon to be function?
int leftover;
float gcd;
int main ()
{
cout<<"Welcome to Brian Garnadi's Version of GCD!\n"<<endl;
cout<<"Enter the first integer to be calculated: ";
cin>> a;
cout<<"Now enter the second integer: ";
cin>>b;
if (a>b)//Determines bigger number
{temp=a;
hold=b;
}
if (a<b)//Determines smaller number
{
temp=b;
hold=a;
}
leftover= temp%hold;
cout<<"\nThe remainder of the two numbers divided is "<<leftover<<".\n"<<endl;
}

Actually there is no need to calculate bigger number the euclid's algorithm manages itself.
Here's the working code :
#include <iostream>
using namespace std;
int gcd(int m,int n)
{
if(n == 0)
return m;
return gcd(n, m % n);
}
int main()
{
int a,b,answer;
cout<<"Welcome to Brian Garnadi's Version of GCD!\n"<<endl;
cout<<"Enter the first integer to be calculated: ";
cin>> a;
cout<<"Now enter the second integer: ";
cin>>b;
answer = gcd(a,b);
cout << "The GCD of the two numbers is : " << answer << endl;
return 0;
}

Do not forget to handle negative numbers in algorithm.
gcd(m, n) = gcd(n, m%n) when n != 0
= m when n = 0
function:
int gcd(int m, int n) {
if(m == 0 && n == 0)
return -1;
if(m < 0) m = -m;
if(n < 0) n = -n;
int r;
while(n) {
r = m % n;
m = n;
n = r;
}
return m;
}

Related

Find the minimum positive integer divisible by both 2 and N

I am still learning C++ and having an ECPC Competition tomorrow.
You are given a positive integer N. Find the minimum positive integer divisible by both 2 and N.
What should I do in the for loop? (still not completed)
#include <iostream>
using namespace std;
int main()
{
int n;
cin>> n;
for(int i; ???;i++)
return 0;
}
You don't need any loop.
There are two cases. Either N is not divisible by 2, then all integers divisible by N and 2 are of the form
x = N * 2 * y
The smallest of those x has y==1.
The second case is when N is divisible by 2, then all integers divisible by N and 2 are of the form
x = N * y
The smallest of those x has y==1.
TL;DR: Do the maths first!
The result is N if N is divisible by 2, otherwise it's N*2.
int result = (N%2 == 0) ? N : N*2;
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
int main()
{
int i,N;
scanf("%d",&N);
for(i=1;i<100;i++)
{
if(i%2==0&&i%N==0)
{
if(i<12)
{
printf("%d",i);
}
}
}
return 0;
}
you should try using
int i=0;
while(true)
{
i++;
if((i%2==0) && (i%n==0))
{
cout<<i;
break;
}
}

Tips on Improving Efficiency of this Code (Beginner)

I am currently doing a coding exercise and am missing some cases due to the time limit being exceeded. Can I get some tips on how to improve the efficiency of my code? Also if you have any general tips for a beginner I would also appreciate that. The problem is below and thanks.
You are given all numbers between 1,2,…,n except one. Your task is to find the missing number.
Input
The first input line contains an integer n.
The second line contains n−1 numbers. Each number is distinct and between 1 and n (inclusive).
Output
Print the missing number.
Constraints
2≤n≤2⋅105
Example
Input:
5
2 3 1 5
Output:
4
Here is my code:
#include <bits/stdc++.h>
using namespace std;
int missingNumber(vector<int> available, int N) {
for (int i=1; i<=N; i++) {
bool counter = false;
for (int j=0; j<N-1; j++) {
if (i == available[j]) {
counter = true;
}
}
if (counter == false) {
return i;
}
}
}
int main() {
ios_base::sync_with_stdio(0); cin.tie(0);
int N;
cin >> N;
vector<int> available(N-1);
int temp = 0;
for (int i=0; i<N-1; i++) {
cin >> temp;
available[i] = temp;
}
cout << missingNumber(available, N);
}
A very simple solution with O(N) complexity is based on the observation that if the N-1 numbers are all between 1 and N and distinct from each other, then it suffices to:
compute the sum of all these N-1 numbers, so linear complexity
subtract the sum computed at step 1 from the sum of the N numbers from 1 to N, which we know is N * (N + 1) / 2, so O(1) complexity.
here is an answer with two versions to your problem
the first version is using Arithmetic progression formula n*(a1 + an) /2
and then subtract your vector sum with the result of the formula.
double missingNumber_ver1(std::vector<int> available, int N) {
// formula for sum for Arithmetic progression
double sum = N * (available[0]+available[N-2]) /2;
double available_sym = std::accumulate(available.begin(), available.end(), 0); // this is to sum the giving numbers
double missing_num = sum-available_sym;
return missing_num;
}
the second version is to use XOR operator and when there is a xor value that is not 0 that means this is the missing number. I'm also using std::iota to build the comparison vector with range values.
double missingNumber_ver2(std::vector<int> available, int N) {
std::vector<int>tem_vec(N-1);
std::iota(tem_vec.begin(), tem_vec.end(), available[0]);
auto av_it = available.begin();
auto tem_vec_it = tem_vec.begin();
while(!(*av_it ^ *tem_vec_it))
{
av_it++;
tem_vec_it++;
}
return *tem_vec_it;
}
and here is the full code - look that I made few changes also in the main() function
#include <iostream>
#include <numeric>
#include <vector>
double missingNumber_ver1(std::vector<int> available, int N) {
// formula for sum for Arithmetic progression
double sum = N * (available[0]+available[N-2]) /2;
double available_sym = std::accumulate(available.begin(), available.end(), 0);
double missing_num = sum-available_sym;
return missing_num;
}
double missingNumber_ver2(std::vector<int> available, int N) {
std::vector<int>tem_vec(4);
std::iota(tem_vec.begin(), tem_vec.end(), available[0]);
auto av_it = available.begin();
auto tem_vec_it = tem_vec.begin();
while(!(*av_it ^ *tem_vec_it))
{
av_it++;
tem_vec_it++;
}
return *tem_vec_it;
}
int main() {
int N;
std::cin >> N;
std::vector<int> available;
int temp = 0;
for (int i=0; i<N-1; i++) {
std::cin >> temp;
available.push_back(temp);
}
std::cout << "missingNumber_ver1 " << missingNumber_ver1(available, N) << "\n";
std::cout << "missingNumber_ver2 " <<missingNumber_ver2(available, N) << "\n";
}

cpp powers of 2 algorothm

so i want this code to be able to count the exact number of powers of 2 but it won't stop until i put odd number in console , any fixes to my code? Thanks a lot in advance
enter code here :
#include <iostream>
using namespace std;
int main()
{
int a;
int counter=0;
cin >> a;
while(true){
cin >> a;
if(a%2==1)
break;
a/=2;
counter=counter+1;
}
cout << counter;
return 0;
}
You were missing some things:
you were not taking inputs as you want.
your counting procedure was wrong.
Soln:
If a number n is a 2's power, then the and operation of n and
n - 1 must be 0. And in all other cases, the result is not 0. Say,
n = 4 (in binary it is 100)
n - 1 = 3 (in binary it is 11)
n & (n - 1) = 0
100 (4)
& 011 (3)
-----------
000 (0)
use this technique
#include <iostream>
using namespace std;
int main()
{
int tests, a;
int counter = 0;
cin >> tests;
for (int i = 0; i < tests; i++)
{
cin >> a;
if ((a & (a - 1)) == 0)
counter = counter + 1;
}
cout << counter;
return 0;
}
If you want to evaluate all inputs power of two, I would use a double as input in order to get those exponent less than zero (0.5, 0.25, etc.).
With this aim, due to the fact that doubles are expressed in double-precision floating-point format (as defined in IEEE 754-2008 standard), you only should check that the normalized fraction got after descomposing the number with std::frexp (https://en.cppreference.com/w/cpp/numeric/math/frexp) is equal to 0.5:
#include <cmath>
bool isPowerOfTwo(double a)
{
int exp;
return std::frexp(a, &exp) == 0.5;
}
Then the code:
#include <cmath>
#include <iostream>
bool isPowerOfTwo(double a)
{
int exp;
return std::frexp(a, &exp) == 0.5;
}
int main() {
unsigned counter = 0;
while (true) {
double input;
std::cin >> input;
if (!isPowerOfTwo(input)) {
break;
}
counter++;
}
std::cout << "Number of inputs power of 2: " << counter << std::endl;
return 0;
}

Program to calculate square root c++

I am making a C++ program to calculate the square root of a number. This program does not use the "sqrt" math built in operation. There are two variables, one for the number the user will enter and the other for the square root of that number. This program does not work really well and I am sure there is a better way to do so:
Here is my full code:
#include <iostream>
using namespace std;
int main(){
int squareroot = 0;
int number;
cout << "enter a number sp that i can calculate its squareroot" << endl;
cin >> number;
while (squareroot * squareroot != number){
squareroot+=0.1;
}
cout << "the square root is" << squareroot << endl;
return 0;
}
I know there must be a better way. Pls help. Looked through Google but don't understand the complex programs there as I am still a beginner.
Thanks in advance.
Below explanation is given for the integer square root calculation:
In number theory, the integer square root of a positive
integer n is the positive integer m which is the greatest integer less
than or equal to the square root of n
The approach your started is good but needs several correction to make it work:
you are working with int you want to add 1 to squareroot not 0.1
you want to stop your calculation when you squareroot * squareroot is equal or greater than number. Think about the case were the number is 26, you don't have an integer that multiplies itself to 26.
in the case of number equal to 26, do you want to return 5 or 6? After your while loop the value of squareroot will be 6 so you might want to reverse it to 5 (if squareroot * squareroot is different than number)
Below the exemple:
#include <iostream>
using namespace std;
int main(){
int squareroot = 0;
int number;
cout << "enter a number sp that i can calculate its squareroot" << endl;
cin >> number;
while (squareroot * squareroot < number){
squareroot+=1;
}
if (squareroot * squareroot != number) --squareroot;
cout << "the square root is" << squareroot << endl;
return 0;
}
Below a more efficient and elegant way of calculating the square root using binary search principle. O(log(n))
int mySqrt(int x) {
if (x==0) return 0;
int left = 1;
int right = x/2 + 1;
int res;
while (left <= right) {
int mid = left + ((right-left)/2);
if (mid<=x/mid){
left = mid+1;
res=mid;
}
else {
right=mid-1;
}
}
return res;
}
This function uses Nested Intervals (untested) and you can define the accuracy:
#include <math.h>
#include <stdio.h>
double mySqrt(double r) {
double l=0, m;
do {
m = (l+r)/2;
if (m*m<2) {
l = m;
} else {
r = m;
}
}
while(fabs(m*m-2) > 1e-10);
return m;
}
See https://en.wikipedia.org/wiki/Nested_intervals
This function will calculate the floor of square root if A is not a perfect square.This function basically uses binary search.Two things you know beforehand is that square root of a number will be less or equal to that number and it will be greater or equal to 1. So we can apply binary search in that range.Below is my implementation.Let me know if you don't understand anything in the code.Hope this helps.
int sqrt(int A) {
if(A<1)return 0;
if(A==1)return 1;
unsigned long long start,end,mid,i,val,lval;
start = 1;
end = A;
while(start<=end){
mid = start+(end-start)/2;
val = mid*mid;
lval = (mid-1)*(mid-1);
if(val == A)return mid;
else if(A>lval && A<val) return mid-1;
else if(val > A)end = mid;
else if(val < A)start = mid+1;
}
}
The problem with your code, is that it only works if the square root of the number is exactly N*0.1, where N is an integer, meaning that if the answer is 1.4142 and not 1.400000000 exactly your code will fail. There are better ways , but they're all more complicated and use numerical analysis to approximate the answer, the easiest of which is the Newton-Raphson method.
you can use the function below, this function uses the Newton–Raphson method to find the root, if you need more information about the Newton–Raphson method, check this wikipedia article. and if you need better accuracy - but worse performance- you can decrease '0.001' to your likening,or increase it if you want better performance but less accuracy.
float mysqrt(float num) {
float x = 1;
while(abs(x*x - num) >= 0.001 )
x = ((num/x) + x) / 2;
return x;
}
if you don't want to import math.h you can write your own abs():
float abs(float f) {
if(f < 0)
f = -1*f;
return f;
}
Square Root of a number, given that the number is a perfect square.
The complexity is log(n)
/**
* Calculate square root if the given number is a perfect square.
*
* Approach: Sum of n odd numbers is equals to the square root of n*n, given
* that n is a perfect square.
*
* #param number
* #return squareRoot
*/
public static int calculateSquareRoot(int number) {
int sum=1;
int count =1;
int squareRoot=1;
while(sum<number) {
count+=2;
sum+=count;
squareRoot++;
}
return squareRoot;
}
#include <iostream>
using namespace std;
int main()
{
double x = 1, average, s, r;
cout << "Squareroot a Number: ";
cin >> s;
r = s * 2;
for ( ; ; ) //for ; ; ; is to run the code forever until it breaks
{
average = (x + s / x) / 2;
if (x == average)
{
cout << "Answer is : " << average << endl;
return 0;
}
x = average;
}
}
You can try my code :D
the method that i used here is the Babylonian Squareroot Method
which you can find it here https://en.wikipedia.org/wiki/Methods_of_computing_square_roots

Whats wrong with my Prime number Checker?

I created a prime number checking program which checks the user entered number prime or not.
It detects non prime numbers easily, but when we type prime numbers, it crashes!
I think I know why, but don't know how to rectify them...
Here's my Program:
#include "stdafx.h"
#include <iostream>
#include<iomanip>
#include <cmath>
using namespace std;
float Asker()
{
float n;
cin >> n;
return n;
}
int Remainder(int n, int x)
{
int q = n%x;
if (q == 0)
return 1;
else
Remainder(n, x + 1 > n);
/*
Here is the PROBLEM
*/
return 0;
}
int main()
{
cout << "Enter your Number : ";
float n = Asker();
int r = Remainder(n, 2);
if (r == 1)
cout << "That Ain't Prime!\n";
else
cout << "Yep Thats Prime!\n";
main();
return 0;
}
Suppose, when I enter 7, I know that, it checks upto 6, then it should crash!(due to x + 1 > n condition). I don't know how to return 0 when it fails the else condition...
To answer to your question "Whats wrong with my Prime number Checker?" a lot of things are wrong:
Don't call main() in main. That's not how you do recursion
int Remainder(int n, int x) and you call it with a float (cast is missing) then with a bool : Remainder(n, x + 1 > n);
Your asker doesn't need to be a float
About the recursion within main there is two reason:
With this config you'll get an endless loop;
ISO C++ forbids taking address of function '::main'
//#include "stdafx.h" //This is an invalid header.
#include <iostream>
#include<iomanip>
#include <cmath>
using namespace std;
float Asker()
{
float n;
cin >> n;
return n;
}
int Remainder(int n, int x)
{
int q = n%x;
if (q == 0 && n>2 )//'2' have to be excluded.
//otherwise 2%2==0 can set
//'2' as a non prime which is wrong
return 1;
else if(x+1<n)
Remainder(n, x + 1);
/*
Here was the PROBLEM
Remainder(n, x + 1 > n) 'x + 1 > n ' is an invalid paramrter.
*/
else
return 0;
}
int main()
{
cout << "Enter your Number : ";
float n=Asker();
int r=1; //It is essential to initialize r to 1
if(n!=1) //Have to exclude '1'. Otherwise
//It will assign '1' as prime which is wrong
r = Remainder(n, 2);
if (r == 1 )
cout << "That Ain't Prime!\n";
else
cout << "Yep Thats Prime!\n";
//main(); //Why are you calling main again?
return 0;
}
Your first error was " #include "stdafx.h" ". Where'd you get this header?
Then inside int Remainder(int n, int x) function you used recursion and sent an invalid syntax " Remainder(n, x + 1 > n) ". You can't use syntax like x+1>n in a parameter.
After that why are you calling main() inside main function?
And your algorithm needed some touch which I have added and explained in comment.
But you should know that the shortest way to check a prime number is to check n%x==0 till x<=square_root(n).
First of all you don't have to check modulo for all numbers up to n-1: it is sufficient to check modulo up to sqrt(n). Second, you should return 0 from the function if the next divisor to check is larger than sqrt(n). Here is the corrected Remainder function.
int Remainder(int n, int x)
{
int q = n%x;
if (q == 0)
return 1;
else
{
if(x+1 > std::sqrt(n)) return 0;
else return Remainder(n, x + 1);
}
}
Finally, it is better to change the type of n in main and Asker from float to int, and return type of Asker should be int too.
This is not an exhausting list of what's wrong with the prime number checker in focus - just a way to fix it quickly. Essentially, such prime number checker shouldn't use recursion - it's more neat to just iterate over all potential divisors from 2 to sqrt(n).