Check if a number is power of 8 or not

Given a number check whether it is power of 8 or not.

Examples :

Input : n = 64
Output : Yes

Input : 75
Output : No

First solution

We calculate log8(n) of the number if it is an integer, then n is in power of 8. We use trunc(n) function that finds closest integer for a double value.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to check if a number is power of 8
#include <cmath>
#include <iostream>
using namespace std;
  
/* function to check if power of 8 */
bool checkPowerof8(int n)
{
    /* calculate log8(n) */
    double i = log(n) / log(8);
  
    /* check if i is an integer or not */
    return (i - trunc(i) < 0.000001);
}
  
/* driver function */
int main()
{
    int n = 65;
    checkPowerof8(n) ? cout << "Yes" : cout << "No";
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to check if
// a number is power of 8
  
class GFG {
  
    // function to check
    // if power of 8
    static boolean checkPowerof8(int n)
    {
        /* calculate log8(n) */
        double i = Math.log(n) / Math.log(8);
  
        /* check if i is an integer or not */
        return (i - Math.floor(i) < 0.000001);
    }
  
    // Driver Code
    public static void main(String args[])
    {
        int n = 65;
        if (checkPowerof8(n))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
  
// This code is contributed by Sam007

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C#  program to check if
// a number is power of 8
using System;
  
class GFG {
  
    // function to check
    // if power of 8
    static bool checkPowerof8(int n)
    {
  
        // calculate log8(n) */
        double i = Math.Log(n) / Math.Log(8);
  
        // check if i is an integer or not */
        return (i - Math.Floor(i) < 0.000001);
    }
  
    // Driver Code
    static public void Main()
    {
        int n = 65;
  
        if (checkPowerof8(n))
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
    }
}
  
// This code is contributed by akt_mit

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to check if 
// a number is power of 8 
  
// function to check 
// if power of 8 
function checkPowerof8($n
    /* calculate log8(n) */
    $i = log($n) / log(8); 
  
    /* check if i is an integer or not */
    return ($i - floor($i) < 0.000001); 
  
// Driver Code 
$n = 65; 
if(checkPowerof8($n)) 
    echo "Yes"
else
    echo "No"
  
// This code is contributed 
// by Sach_Code
?>

chevron_right