C++で中学校の手順を使用して2つの数値のGCDまたはHCFを見つけるプログラム
このチュートリアルでは、中学校の手順を使用して2つの数値のGCDまたはHCFを見つけるプログラムについて説明します。
このために、2つの番号が提供されます。私たちの仕事は、与えられた値のGCD(最大公約数)またはHCF(最大公約数)を見つけることです。
例
#include <bits/stdc++.h>
#define MAXFACTORS 1024
using namespace std;
//structure to store factorization
typedef struct{
int size;
int factor[MAXFACTORS + 1];
int exponent[MAXFACTORS + 1];
} FACTORIZATION;
void FindFactorization(int x, FACTORIZATION* factorization){
int i, j = 1;
int n = x, c = 0;
int k = 1;
factorization->factor[0] = 1;
factorization->exponent[0] = 1;
for (i = 2; i <= n; i++) {
c = 0;
while (n % i == 0) {
c++;
n = n / i;
}
if (c > 0) {
factorization->exponent[k] = c;
factorization->factor[k] = i;
k++;
}
}
factorization->size = k - 1;
}
//printing the factors
void DisplayFactorization(int x, FACTORIZATION factorization){
int i;
cout << "Prime factor of << x << = ";
for (i = 0; i <= factorization.size; i++) {
cout << factorization.factor[i];
if (factorization.exponent[i] > 1)
cout << "^" << factorization.exponent[i];
if (i < factorization.size)
cout << "*";
else
cout << "\n";
}
}
//gcd using Middle School procedure
int gcdMiddleSchoolProcedure(int m, int n){
FACTORIZATION mFactorization, nFactorization;
int r, mi, ni, i, k, x = 1, j;
FindFactorization(m, &mFactorization);
DisplayFactorization(m, mFactorization);
FindFactorization(n, &nFactorization);
DisplayFactorization(n, nFactorization);
int min;
i = 1;
j = 1;
while (i <= mFactorization.size && j <= nFactorization.size) {
if (mFactorization.factor[i] < nFactorization.factor[j])
i++;
else if (nFactorization.factor[j] < mFactorization.factor[i])
j++;
else{
min = mFactorization.exponent[i] > nFactorization.exponent[j] ? nFactorization.exponent[j] : mFactorization.exponent[i];
x = x * mFactorization.factor[i] * min;
i++;
j++;
}
}
return x;
}
int main(){
int m = 10, n = 15;
cout << "GCD(" << m << ", " << n << ") = " << gcdMiddleSchoolProcedure(m, n);
return (0);
} 出力
GCD(10, 15) = Prime factor of << x << = 1*2*5 Prime factor of << x << = 1*3*5 5
-
GCDを見つけるためのC++プログラム
2つの数値の最大公約数(GCD)は、両方を除算する最大の数値です。 例:45と27の2つの数字があるとします。 45 = 5 * 3 * 3 27 = 3 * 3 * 3 したがって、45と27のGCDは9です。 2つの数値のGCDを見つけるプログラムは次のとおりです。 例 #include <iostream> using namespace std; int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } int
-
2つの数値のGCDを見つけるJavaプログラム
この記事では、Javaで2つの数値のGCDを見つける方法を理解します。 2つの数値の最大公約数(GCD)は、両方を除算する最大の数値です。 以下は同じのデモンストレーションです- 入力 入力が-であると仮定します Value_1 : 18 Value_2 : 24 出力 必要な出力は-になります GCD of the two numbers : 6 アルゴリズム Step1- Start Step 2- Declare three integers: input_1, inpur_2 and gcd Step 3- Prompt the user to enter two in