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 lcm() two find out lcm of n numbers
gcd(number1, number2)
Declare r, a, b
Assign r=0
a = (number1 greater than number2)? number1: number2
b = (number1 less than number2)? number1: number2
r = b
While (a mod b not equal to 0)
Do
r = a mod b
a=b
b=r
Return r
Done
lcm(number1, number2)
Declare a
a=(number1 greater than number2)?number1:number2
While(true) do
If
(a mod number1 == 0 and a number2 == 0)
Return a
Increment a
Done
End サンプルコード
#include<iostream>
using namespace std;
int gcd(int m, int n) {
int r = 0, a, b;
a = (m > n) ? m : n;
b = (m < n) ? m : n;
r = b;
while (a % b != 0) {
r = a % b;
a = b;
b = r;
}
return r;
}
int lcm(int m, int n) {
int a;
a = (m > n) ? m: n;
while (true) {
if (a % m == 0 && a % n == 0)
return a;
++a;
}
}
int main(int argc, char **argv) {
cout << "Enter the two numbers: ";
int m, n;
cin >> m >> n;
cout << "The GCD of two numbers is: " << gcd(m, n) << endl;
cout << "The LCM of two numbers is: " << lcm(m, n) << endl;
return 0;
} 出力
Enter the two numbers: 7 6 The GCD of two numbers is: 1 The LCM of two numbers is: 42
-
C++で三角形の図心を見つけるプログラム
この問題では、三角形の3つの頂点の座標を示す2D配列が与えられます。私たちのタスクは、C++で三角形のセントロイドを見つけるプログラムを作成することです。 セントロイド 三角形の3つの中央値は、三角形の3つの中央値が交差する点です。 中央値 三角形の頂点は、三角形の頂点とその反対側の線の中心点を結ぶ線です。 問題を理解するために例を見てみましょう 入力 (-3, 1), (1.5, 0), (-3, -4) 出力 (-3.5, -1) 説明 Centroid (x, y) = ((-3+2.5-3)/3, (1 + 0 - 4)/3) = (-3.5, -1) ソリューションアプロ
-
C++で平行四辺形の面積を見つけるプログラム
この問題では、平行四辺形の底と高さを表す2つの値が与えられます。私たちのタスクは、C++で平行四辺形の領域を見つけるプログラムを作成することです。 平行四辺形 は、反対側が等しく平行な4辺の閉じた図形です。 問題を理解するために例を見てみましょう 入力 B = 20, H = 15 出力 300 説明 平行四辺形の面積=B* H =20 * 15 =300 ソリューションアプローチ この問題を解決するために、平行四辺形の面積の幾何学的公式を使用します。 Area = base * height. ソリューションの動作を説明するプログラム 例 #include <io