# Embedded C to find the number of one's in a given 32bit number and optimize the code

## Embedded C to find the number of one’s in a given 32bit number and optimize the code

In this article let’s learn how to optimize a program.The program which is used for optimization is to find number of ones in a given 32bit number. First let’s write a simple code and then let’s see how to optimize it.

### Algorithm:

1)Start
2)Assign the 32bit number
3)Divide the number by 2 and store it’s remainder
4)Compare the remainder to 1 and update the counter if it is true
5)divide the number by 2 and update the number by it’s quotient
6)Repeat the step 3,4 and 5 by 32 times as it is 32 bit number
7)Stop

### Alternate method:

I know this program will give you correct results but what if the number is too small don’t you think the processor will unnecessarily goes into 32 loops.So here is another logic to reduce number of loops.

### Algorithm:

1)Start
2)Logical AND the number with 1 and check if the number is 1 so that it checks the lowest bit of number
3)Right shift the number by one unit
4)Repeat the step 2 and 3 until the number is equal to 0
5)Stop

### Alternate method:

You know guys you can further reduce the program by looping the binary number according to the number of ones in the program.

### Algorithm:

1)Start
2)Logical AND the number by number-1
3)If the number is greater than zero increment the counter
3)Repeat until the number is zero
4)Stop

### Conclusion:

We can see in the above program as we reduce the number of loops and decrease the number of lines of the program the execution time of the processor increases and the memory decreases.