C++で指定されたGCDとLCMのペアを検索します
このセクションでは、指定されたGCD値とLCM値を使用してペアの数を取得する方法を説明します。 GCDとLCMの値が2と12であると仮定します。これで、可能な数値のペアは(2、12)、(4、6)、(6、4)、および(12、2)になります。したがって、私たちのプログラムはペアの数を見つけます。それは4です。
この問題を解決するための手法を理解するためのアルゴリズムを見てみましょう。
アルゴリズム
countPairs(gcd, lcm): Begin if lcm is nit divisible by gcd, then return 0 temp := lcm/gcd c := primeFactorCount(temp) res := shift 1 to the left c number of times return res End primeFactorCount(n): Begin count := 0 until n is not odd, increase count and divide n by 2 for i := 3, when i2 < n, increase i by 2, do if n is divisible by i, then increase count while n is divisible by i, do n := n / i done end if done if n > 2, then increase count by 1 return count End
例
#include<iostream>
#include<cmath>
using namespace std;
int primeFactorCount(int);
int countPairs(int gcd, int lcm) {
if(lcm % gcd != 0)
return 0;
int temp = lcm/gcd;
return (1 << primeFactorCount(temp));
}
int primeFactorCount(int n){
int count = 0;
if(n%2 == 0){ //if n is divisible by 0, enter into the next part
count++;
while(n%2 == 0)
n = n/2;
}
//now n is odd, so if we increase n by 2, all numbers will be odd
for(int i = 3; i*i <= n; i = i + 2){
if(n%i == 0){ //if n is divisible by 0, enter into the next part
count++;
while(n%i == 0)
n = n/i;
}
}
if(n > 2)
count++;
return count;
}
int main() {
cout << "Possible pairs of GCD = 2, and LCM = 12 is " <<countPairs(2, 12);
} 出力
Possible pairs of GCD = 2, and LCM = 12 is 4
-
C++の平衡二分探索木で与えられた合計を持つペアを見つけます
平衡二分探索木とターゲット合計があるとすると、合計がターゲット合計に等しいペアであるかどうかをチェックするメソッドを定義する必要があります。この場合。二分探索木は不変であることに注意する必要があります。 したがって、入力が次のような場合 その場合、出力は(9 + 26 =35)になります。 これを解決するには、次の手順に従います- スタックs1、s2を定義する done1:=false、done2:=false val1:=0、val2:=0 curr1:=root、curr2:=root 無限ループ、実行- done1がfalseの場合、do − curr1が
-
n個の数のGCDとLCMを見つけるためのC++プログラム
これは、n個の数のGCDとLCMを見つけるためのコードです。すべてがゼロではない2つ以上の整数のGCDまたは最大公約数は、各整数を除算する最大の正の整数です。 GCDは最大公約数としても知られています。 2つの数値の最小公倍数(LCM)は、両方の数値の倍数である最小公倍数(ゼロではない)です。 アルゴリズム Begin Take two numbers as input Call the function gcd() two find out gcd of n numbers Call the function l