Find the value of N when F(N) = f(a)+f(b) where a+b is the minimum possible and a*b = N
Last Updated :
21 Jun, 2022
Given an integer N, the task is to find the value of F(N) if:
- F(1) = 0
- F(2) = 2
- F(N) = 0, if N is odd prime.
- F(N) = F(a) + F(b), where a and b are factors of N and (a + b) is minimum among all factors. Also, a * b = N
Examples:
Input: N = 5
Output: 0
Since 5 is an odd prime.
Input: N = 4
Output: 4
4 can be written as 2 * 2, hence f(2) + f(2) = 4
Input: N = 20
Output: 4
20 can be written as f(4) + f(5), and f(4) can be written as f(2) + f(2), which is 4.
Approach: The following steps can be followed to solve the problem:
- If N is 1 or 2, the answer is 0 or 2 respectively.
- On breaking the recurrence f(n) = f(a) + f(b), we get it is the number of times a number is divisible by 2.
- The answer for f(n) is 2 * (number of times a number is divisible by 2)
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int getValueOfF( int n)
{
if (n == 1)
return 0;
if (n == 2)
return 1;
int cnt = 0;
while (n % 2 == 0) {
cnt += 1;
n /= 2;
}
return 2 * cnt;
}
int main()
{
int n = 20;
cout << getValueOfF(n);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int getValueOfF( int n)
{
if (n == 1 )
return 0 ;
if (n == 2 )
return 1 ;
int cnt = 0 ;
while (n % 2 == 0 )
{
cnt += 1 ;
n /= 2 ;
}
return 2 * cnt;
}
public static void main (String[] args)
{
int n = 20 ;
System.out.println (getValueOfF(n));
}
}
|
Python3
def getValueOfF(n):
if (n = = 1 ):
return 0
if (n = = 2 ):
return 1
cnt = 0
while (n % 2 = = 0 ):
cnt + = 1
n / = 2
return 2 * cnt
n = 20
print (getValueOfF(n))
|
C#
using System;
class GFG
{
static int getValueOfF( int n)
{
if (n == 1)
return 0;
if (n == 2)
return 1;
int cnt = 0;
while (n % 2 == 0)
{
cnt += 1;
n /= 2;
}
return 2 * cnt;
}
static public void Main ()
{
int n = 20;
Console.WriteLine(getValueOfF(n));
}
}
|
PHP
<?php
function getValueOfF( $n )
{
if ( $n == 1)
return 0;
if ( $n == 2)
return 1;
$cnt = 0;
while ( $n % 2 == 0)
{
$cnt += 1;
$n /= 2;
}
return 2 * $cnt ;
}
$n = 20;
echo getValueOfF( $n );
?>
|
Javascript
<script>
function getValueOfF(n)
{
if (n == 1)
return 0;
if (n == 2)
return 1;
let cnt = 0;
while (n % 2 == 0)
{
cnt += 1;
n = parseInt(n / 2, 10);
}
return 2 * cnt;
}
let n = 20;
document.write(getValueOfF(n));
</script>
|
Time Complexity: O(log n), as we are using a loop to traverse and in each traversal we are decrementing n by floor division of 2 therefore the effective time will be 1+1/2+1/4+…..+1/2^n which is equivalent to log(n).
Auxiliary Space: O(1), as we are not using any extra space.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...