Check if Decimal representation of an Octal number is divisible by 7
Given an Octal number N. The task is to write a program to check if the Decimal representation of the given octal number N is divisible by 7 or not.
Examples:
Input: N = 112
Output: NO
Equivalent Decimal = 74
7410 = 7 * 10 1 + 4 * 100
1128 = 1 * 82 + 1 * 81 + 2 * 80
Input: N = 25
Output: YES
Decimal Equivalent = 21
The idea is to note that, 8 % 7 will return 1. Thus, when we expand octal representation and take its modulo 7 all powers of 8 in individual terms will reduce to 1. So, if the sum of all the digits in octal representation is divisible by 7 then, the corresponding decimal number will be divisible by 7.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int check( int n)
{
int sum = 0;
while (n != 0) {
sum += n % 10;
n = n / 10;
}
if (sum % 7 == 0)
return 1;
else
return 0;
}
int main()
{
int n = 25;
(check(n) == 1) ? cout << "YES"
: cout << "NO" ;
return 0;
}
|
Java
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
static int check( int n)
{
int sum = 0 ;
while (n != 0 )
{
sum += n % 10 ;
n = n / 10 ;
}
if (sum % 7 == 0 )
return 1 ;
else
return 0 ;
}
public static void main(String args[])
{
int n = 25 ;
String s=(check(n) == 1 ) ?
"YES" : "NO" ;
System.out.println(s);
}
}
|
Python 3
def check(n):
sum = 0
while n ! = 0 :
sum + = n % 10
n = n / / 10
if sum % 7 = = 0 :
return 1
else :
return 0
if __name__ = = "__main__" :
n = 25
print (( "YES" ) if check(n) = = 1
else print ( "NO" ))
|
C#
using System;
class GFG
{
static int check( int n)
{
int sum = 0;
while (n != 0)
{
sum += n % 10;
n = n / 10;
}
if (sum % 7 == 0)
return 1;
else
return 0;
}
public static void Main(String []args)
{
int n = 25;
String s=(check(n) == 1) ?
"YES" : "NO" ;
Console.WriteLine(s);
}
}
|
PHP
<?php
function check( $n )
{
$sum = 0;
while ( $n != 0)
{
$sum += $n % 10;
$n = (int)( $n / 10);
}
if ( $sum % 7 == 0)
return 1;
else
return 0;
}
$n = 25;
(check( $n ) == 1) ?
print ( "YES\n" ) :
print ( "NO\n" );
?>
|
Javascript
<script>
function check(n)
{
let sum = 0;
while (n != 0) {
sum += n % 10;
n = Math.floor(n / 10);
}
if (sum % 7 == 0)
return 1;
else
return 0;
}
let n = 25;
(check(n) == 1) ? document.write( "YES" )
: document.write( "NO" );
</script>
|
Time Complexity: O(log10n)
Auxiliary Space: O(1)
Last Updated :
08 Sep, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...