Round to next smaller multiple of 8

Given an unsigned integer x. Round it down to the next smaller multiple of 8 using bitwise operations only.

Examples:

Input : 35
Output : 32

Input : 40
Output : 40 
As 40 is already a multiple of 8. So, no 
modification is done.

Solution 1: A naive approach to solve this problem using arithmetic operators is :
Let x be the number then,
x = x – (x % 8)
This will round down x to the next smaller multiple of 8. But we are not allowed to use arithmetic operators.

Solution 2: An efficient approach to solve this problem using bitwise AND operation is: x = x & (-8)
This will round down x to the next smaller multiple of 8. The idea is based on the fact that last three bits in a multiple of 8 must be 0,

Below is the implementation of above idea:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to find next smaller
// multiple of 8.
#include <bits/stdc++.h>
using namespace std;
  
int RoundDown(int& a)
{
    return a & (-8);
}
  
int main()
{
    int x = 39;
    cout << RoundDown(x);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

//Java program to find next smaller
// multiple of 8.
  
import java.io.*;
  
class GFG {
static int RoundDown(int a)
{
    return a & (-8);
}
  
    public static void main (String[] args) {
  
    int x = 39;
    System.out.println (RoundDown(x));
    }
}
//This Code is Contributed by ajit

chevron_right


Python3

# Python 3 program to find next
# smaller multiple of 8.

def RoundDown(a):
return a & (-8)

# Driver Code
if __name__ == ‘__main__’:
x = 39
print(RoundDown(x))

# This code is contributed
# by Surendra_Gangwar

C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find next smaller
// multiple of 8.
using System;
  
class GFG
{
static int RoundDown(int a)
{
    return a & (-8);
}
  
public static void Main()
{
    int x = 39;
    Console.Write(RoundDown(x));
}
}
  
// This code is contributed
// by Akanksha Rai

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to find next smaller 
// multiple of 8. 
  
function RoundDown($a
    return ($a & (-8)); 
  
// Driver Code
$x = 39; 
echo RoundDown($x); 
  
// This code is contributed by jit_t
?>

chevron_right


Output:

32

Time Complexity: The time complexity of this approach is O(1)
Space Complexity: The space complexity of this approach is O(1)



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.