Cプログラムで2^X –1の形式で数値を作成するための手順を印刷します。
数値nが与えられた場合、Xor演算を使用して2^X-1の形式で数値を作成する手順を印刷する必要があります。
- 数値を2^ M-1とXORする必要があります 、ここで M 奇妙なステップで、あなたが選択します。
- 偶数ステップで数値を1ずつ増やします
nが2^X-1になるまでステップを実行し続け、すべてのステップを印刷します
例
Input: 22 Output: Step 1 : Xor with 15 Step 2: Increase by 1 Step 3 : Xor with 7 Step 4: Increase by 1 Step 5 : Xor with 1 Input:7 Output: No Steps to be performed
アルゴリズム
int find_leftmost_unsetbit(int n) START STEP 1 : DECLARE AND ASSIGN ind = -1, i = 1 STEP 2 : LOOP WHILE n IF !(n & 1) THEN, ASSIGN ind WITH i END IF INCREMENT i BY 1 LEFT SHIFT n BY 1 END WHILe STEP 3 : RETURN ind STOP void perform_steps(int n) START STEP 1 : DECLARE AND ASSIGN left = find_leftmost_unsetbit(n) STEP 2 : IF left == -1 THEN, PRINT "No Steps to be performed" RETURN END IF STEP 3 : DECLARE AND ASSIGN step = 1 STEP 4 : LOOP WHILE find_leftmost_unsetbit(n) != -1 IF step % 2 == 0 THEN, INCREMENT n BY 1 PRINT "Step n : Increase by 1\n" ELSE DECLARE AND ASSIGN m = find_leftmost_unsetbit(n) AND SET num = (pow(2, m) - 1) SET n = n ^ num PRINT "Step N : Xor with Num END IF INCREMENT step BY 1 END LOOP STOP
例
#include <stdio.h>
#include <math.h>
//To find the leftmost bit
int find_leftmost_unsetbit(int n){
int ind = -1;
int i = 1;
while (n) {
if (!(n & 1))
ind = i;
i++;
n >>= 1;
}
return ind;
}
void perform_steps(int n){
// Find the leftmost unset bit
int left = find_leftmost_unsetbit(n);
//If there is no bit
if (left == -1) {
printf("No Steps to be performed\n");
return;
}
// To count the number of steps
int step = 1;
// Iterate till number is in form of 2^x - 1
while (find_leftmost_unsetbit(n) != -1) {
// if the step is even then increase by 1
if (step % 2 == 0) {
n += 1;
printf("Step %d: Increase by 1\n", step);
}
// if the step is odd then xor with 2^m-1
else {
// Finding the leftmost unset bit
int m = find_leftmost_unsetbit(n);
int num = (int)(pow(2, m) - 1);
n = n ^ num;
printf("Step %d : Xor with %d\n", step, num);
}
// To increase the steps
step += 1;
}
}
int main(){
int n = 22;
perform_steps(n);
return 0;
} 出力
上記のプログラムを実行すると、次の出力が生成されます-
Step 1 : Xor with 15 Step 2 : Increase by 1 Step 3 : Xor with 7 Step 4 : Increase by 1 Step 5 : Xor with 1
-
Cで数字パターンを印刷するプログラム
プログラムの説明 数値パターンは、パターンルールと呼ばれるルールに基づいて作成された一連の数字です。パターンルールでは、1つ以上の数学演算を使用して、シーケンス内の連続する数字間の関係を記述できます。 パターンの例 パターン1 1 2 6 3 7 10 4 8 11 13 5 9 12 14 15 パターン2 1 1 2 3 1 2 3 4 5 1 2 3 4 5 6 7 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 1 2 3 4 5 1 2 3 1 アルゴリズム Pattern 1
-
正方行列をCでZ形式で印刷するプログラム
プログラムの説明 正方行列の要素をZ形式で印刷します 正方行列は、同じ数の行と列を持つ行列です。 n行n列の行列は次数の正方行列として知られています アルゴリズム To print the elements of the Square Matrix in Z form We need to print the first row of matrix then diagonal and then last row of the square matrix. 例 /* Program to print a square matrix in Z form */ #include<st