chore(C): added bit-manipulation (#348)

Co-authored-by: ven0m-hue <venkatesh17nayak@gmail.com>
pull/354/head
ven0m-hue 2021-06-11 00:17:56 +05:30 committed by GitHub
parent d2843f029b
commit 0a4015ef93
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 122 additions and 0 deletions

View File

@ -4,6 +4,11 @@
- [Even and Odd](arrays/even-and-odd.c)
- [Unique Elements in an array](arrays/unique-elements-in-an-array.c)
## Bit Manipulation
- [Add and Subtract](bit-manipulation/add-and-sub-bitwise)
- [Multiply](bit-manipulation/multiply-bitwise)
- [divide](bit-manipulation/divide-bitwise)
## Graphs
- [Prim's Algorithm](graphs/Prim's-algorithm.c)

View File

@ -0,0 +1,50 @@
// function to add, sub without using the operators
#include <stdio.h>
// Prototypes
int add(int, int);
int sub(int, int);
int main() {
int a, b;
printf("Enter two integers\n");
scanf("%d %d", &a, &b);
int s,d;
d = add(a,b);
s = sub(a,b);
printf("%d %d",s,d); // output 2 and 10
return 0;
}
// function to add
int add(int a, int b)
{
int c = 0; //carry
while(b !=0)
{
c = a&b;
a = a^b;
b = c<<1;
}
return a;
}
// function to sub
int sub(int a, int b)
{
int s,d;
d = add((~b),1);
s = add(a,d);
return s;
} // subtraction is addition in disguise (just flip the subtracting term and that's what this function does.)

View File

@ -0,0 +1,37 @@
// Program to divide a number without using the operator '/'
#include <stdio.h>
#include <stdlib.h>
int division(int A, int B);
int main() {
// your code goes here
int a, b;
printf("Enter the two integers");
scanf("%d %d", &a, &b);
printf("The division is %d",division(a,b)); // Returns the floored output.
}
int division(int divisor, int dividend)
{
int a = abs(divisor);
int b = abs(dividend);
int result = 0;
while(a-b>=0)
{
int x=0; // b<<0
while(a -(b<<x<<1)>=0)
{
x++;
}
result += 1<<x;
a -= b<<x;
}
return (divisor>0) == (dividend>0) ? result : -result ;
}

View File

@ -0,0 +1,30 @@
// Shift and add algo for multiplication without using multiplication operator
#include <stdio.h>
#include <stdlib.h>
int main() {
// your code goes here
int mA, mB;
printf("Enter the two inputs\n");
scanf("%d %d", &mA, &mB);
int a = 0, m0 = 0, m1 = 0;
m0 = mA > 0 ? mA : abs(mA); // negative input.
m1 = mB > 0 ? mB : abs(mB);
while(m1)
{
if((m1 & 0x01))
a += m0;
m0 <<= 1;
m1 >>= 1;
}
if(mA < 0 || mB < 0)
a = -a;
printf("The product is %d", a);
return 0;
}