特定のケースで整数分割を実行するC++プログラム
これは、特定の場合に整数分割を実行するC++プログラムです。このプログラムでは、正の整数nが与えられ、nを正の整数の合計として表すためのすべての可能な一意の方法を生成する必要があります。
アルゴリズム
Begin function displayAllUniqueParts(int m): 1) Set Index of last element k in a partition to 0 2) Initialize first partition as number itself, p[k]=m 3) Create a while loop which first prints current partition, then generates next partition. The loop stops when the current partition has all 1s. 4) Display current partition as displayArray(p, k + 1) 5) Generate next partition: 6) Initialize val = 0. Find the rightmost non-one value in p[]. Also, update the val so that we know how much value can be ccommodated. If k < 0, All the values are 1 so there are no more partitions Decrease the p[k] found above and adjust the val. 7) If val is more, then the sorted order is violated. Divide val in different values of size p[k] and copy these values at different positions after p[k]. Copy val to next position and increment position. End
例
#include<iostream> using namespace std; void displayArray(int p[], int m) { //to print the array for (int i = 0; i < m; i++) cout << p[i] << " "; cout << endl; } void displayAllUniqueParts(int m) { int p[m]; int k = 0; p[k] = m; while (true) { displayArray(p, k + 1); int val = 0; // initialize val while (k >= 0 && p[k] == 1) { val += p[k]; // update val k--; } if (k < 0) return; p[k]--; val++; //if val is more while (val > p[k]) { p[k + 1] = p[k]; val = val - p[k]; k++; } p[k + 1] = val; k++; } } int main() { cout << "Display All Unique Partitions of integer:7\n"; displayAllUniqueParts(7); return 0; }
出力
Display All Unique Partitions of integer:7 7 6 1 5 2 5 1 1 4 3 4 2 1 4 1 1 1 3 3 1 3 2 2 3 2 1 1 3 1 1 1 1 2 2 2 1 2 2 1 1 1 2 1 1 1 1 1 1 1 1 1 1 1 1
-
C++での八面体の表面積のプログラム
八面体とは何ですか? 「十二面体」という言葉はギリシャ語に由来し、オクタは「8」を意味し、ヘドロンは「顔」を意味します。幾何学的な八面体は、8つの面を持つ3Dプラトニックまたは正多角形です。同様に、他の図の八面体にもプロパティがあり、それは- 6つの多面体頂点 12の多面体エッジ 8つの正三角形 以下は八面体の図です 問題 側面を指定すると、プログラムは八面体の表面積を見つける必要があります。表面積は、指定された図形の面が占める総スペースです。 八面体の表面積を計算するには、次の式があります- ここで、aは八面体の側面です 例 Input-: side=5 Outpu
-
QuickSort用のC++プログラム?
クイックソートは、比較を使用してソートされていないリスト(配列)をソートするソート手法です。クイックソートは、パーティション交換ソートとも呼ばれます。 等しいソート項目の相対的な順序が保持されないため、安定したソートではありません。クイックソートは配列を操作できるため、ソートを実行するために少量の追加メモリが必要です。常に最悪の場合のパーティションを選択するわけではないことを除いて、選択ソートと非常によく似ています。したがって、選択ソートのより適切な形式と見なすことができます。 QuickSortは、最も効率的な並べ替えアルゴリズムの1つであり、配列を小さい配列に分割することに基づいていま