Greatest odd factor of an even number
Last Updated :
03 Oct, 2022
Given an even number N, the task is to find the greatest possible odd factor of N.
Examples:
Input: N = 8642
Output: 4321
Explanation:
Here, factors of 8642 are {1, 8642, 2, 4321, 29, 298, 58, 149} in which odd factors are {1, 4321, 29, 149} and the greatest odd factor among all odd factors is 4321.
Input: N = 100
Output: 25
Explanation:
Here, factors of 100 are {1, 100, 2, 50, 4, 25, 5, 20, 10} in which odd factors are {1, 25, 5} and the greatest odd factor among all odd factors is 25.
Naive Approach: The naive approach is to find all the factors of N and then select the greatest odd factor from it.
Time Complexity: O(sqrt(N))
Efficient Approach: The efficient approach for this problem is to observe that every even number N can be represented as:
N = 2i*odd_number
Therefore to get the largest odd number we need to divide the given number N by 2 until N becomes an odd number.
Below is the implementation of the above approach:
C++
#include<bits/stdc++.h>
using namespace std;
int greatestOddFactor( int n)
{
int pow_2 = ( int )( log (n));
int i = 1;
while (i <= pow_2)
{
int fac_2 = (2 * i);
if (n % fac_2 == 0)
{
if ((n / fac_2) % 2 == 1)
{
return (n / fac_2);
}
}
i += 1;
}
}
int main()
{
int N = 8642;
cout << greatestOddFactor(N);
return 0;
}
|
Java
class GFG{
public static int greatestOddFactor( int n)
{
int pow_2 = ( int )(Math.log(n));
int i = 1 ;
while (i <= pow_2)
{
int fac_2 = ( 2 * i);
if (n % fac_2 == 0 )
{
if ((n / fac_2) % 2 == 1 )
{
return (n / fac_2);
}
}
i += 1 ;
}
return 0 ;
}
public static void main(String[] args)
{
int N = 8642 ;
System.out.println(greatestOddFactor(N));
}
}
|
Python3
import math
def greatestOddFactor(n):
pow_2 = int (math.log(n, 2 ))
i = 1
while i < = pow_2:
fac_2 = ( 2 * * i)
if (n % fac_2 = = 0 ) :
if ( (n / / fac_2) % 2 = = 1 ):
print (n / / fac_2)
break
i + = 1
N = 8642
greatestOddFactor(N)
|
C#
using System;
class GFG{
public static int greatestOddFactor( int n)
{
int pow_2 = ( int )(Math.Log(n));
int i = 1;
while (i <= pow_2)
{
int fac_2 = (2 * i);
if (n % fac_2 == 0)
{
if ((n / fac_2) % 2 == 1)
{
return (n / fac_2);
}
}
i += 1;
}
return 0;
}
public static void Main(String[] args)
{
int N = 8642;
Console.WriteLine(greatestOddFactor(N));
}
}
|
Javascript
<script>
function greatestOddFactor(n)
{
let pow_2 = (Math.log(n));
let i = 1;
while (i <= pow_2)
{
let fac_2 = (2 * i);
if (n % fac_2 == 0)
{
if ((n / fac_2) % 2 == 1)
{
return (n / fac_2);
}
}
i += 1;
}
return 0;
}
let N = 8642;
document.write(greatestOddFactor(N)); ;
</script>
|
Time Complexity: O(log2(N))
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...