# Calculate 7n/8 without using division and multiplication operators

Given an integer, write a function that calculates ⌈7n/8⌉ (ceiling of 7n/8) without using division and multiplication operators.

We strongly recommend to minimize your browser and try this yourself first.

Method 1:
The idea is to first calculate floor of n/8, i.e., ⌊n/8⌋ using right shift bitwise operator. The expression n>>3 produces the same.

If we subtract ⌊n/8⌋ from n, we get ⌈7n/8⌉

Below is C program based on above idea.

```// C program to evaluate ceil(7n/8) without using * and /
#include<stdio.h>

int multiplyBySevenByEight(unsigned int n)
{
/* Note the inner bracket here. This is needed
because precedence of '-' operator is higher
than '<<' */
return (n - (n>>3));
}

/* Driver program to test above function */
int main()
{
unsigned int n = 9;
printf("%d", multiplyBySevenByEight(n));
return 0;
}
```

Output:

`8`

Method 2 (Always matches with 7*n/8):
The above method doesn’t always produce result same as “printf(“%u”, 7*n/8)”. For example, the value of expression 7*n/8 is 13 for n = 15, but above proogram produces 14. Below is modified version that always matches 7*n/8. The idea is to first multiply the number with 7, then divide by 8 as it happens in expression 7*n/8.

```// C program to evaluate 7n/8 without using * and /
#include<stdio.h>

int multiplyBySevenByEight(unsigned int n)
{
/* Step 1) First multiply number by 7 i.e. 7n = (n << 3) -n
* Step 2) Divide result by 8 */
return ((n << 3) -n) >> 3;
}

/* Driver program to test above function */
int main()
{
unsigned int n = 15;
printf("%u", multiplyBySevenByEight(n));
return 0;
}
```

Output:

`13`

Note :
There is difference between outcomes of two methods. The method 1 produces ceil(7n/8), but method two produces integer value of 7n/8. For example, for n = 15, outcome of first method is 14, but for second method is 13.

Thanks to Narendra Kangralkar for suggesting this method.

# GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.
3 Average Difficulty : 3/5.0
Based on 7 vote(s)

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.