Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Smaller and faster way to calculate modulus of 2 using bit manipulation #382

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions algorithms/bit-manipulation/addition.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#include <stdio.h>

int add(int x, int y)
{
while(x > 0)
{
unsigned int carry = x & y;
y = x ^ y;
x = carry << 1;
}
return y;
}

int main()
{
printf("sum of %d and %d is %d\n", 3, 4, add(3, 4));
return 0;
}


15 changes: 15 additions & 0 deletions algorithms/bit-manipulation/check_power_of_2.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#include <stdio.h>

#define check_power_of_2(x) (!( x & (x - 1)) && (x > 1))

int main()
{
for(int i = 1; i < 100; i++)
{
if(check_power_of_2(i))
printf("True! %d is a power of 2\n", i);
else
printf("False! %d is not a power of 2\n", i);
}
printf("Hello World\n");
}
20 changes: 20 additions & 0 deletions algorithms/bit-manipulation/modulus_with_power_of_2.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/*
1. Here is an example of the modulus operation
using bit manipulation
2. It is supposed to be much faster and more efficient
The only condition is that n should be a power of 2
*/

#include <stdio.h>

#define modulo(x,n) ((x) & (n - 1))

int main()
{
printf("Hello World\n");

for(int i = 0; i < 100; i++)
printf("value of %d modulo 8 is: %d\n", i, modulo(i,10));

return 0;
}
18 changes: 18 additions & 0 deletions algorithms/bit-manipulation/subtraction.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
#include <stdio.h>

int subtract(int x, int y)
{
while(y != 0)
{
unsigned int borrow = y & ~x;
x = y ^ x;
y = borrow << 1;
}
return x;
}

int main()
{
printf("diff of %d and %d is %d\n", 4, 3, subtract(4, 3));
return 0;
}