Number formed after K times repeated addition of smallest divisor of N
Last Updated :
22 Feb, 2023
Given two integers N and K, the task is to generate the final outcome of performing K operations which involves adding the smallest divisor, other than 1, of the current value of N to it at every step.
Example:
Input: N = 9, K = 4
Output: 18
Explanation:
Divisors of 9 are {1, 3, 9}
1st Operation: N = 9 + 3 = 12
2nd Operation: N = 12 + 2 = 14
3rd Operation: N = 14 + 2 = 16
4th Operation: N = 16 + 2 = 18
Input: N = 16, K = 3
Output: 22
Naive Approach: The brute force approach for this problem is to perform the operation K times and then print the final number.
Efficient Approach: The trick here is that if the given N is even, smallest divisor will be always 2 for all the K operations. Hence, the required Kth number will be simply
required number = N + K * 2
Also if N is odd, the smallest divisor will be odd. Hence adding them will result in an even value (odd + odd = even). Therefore now the above trick can be applied for (K-1) operations, i.e.,
required number = N + smallest divisor of N + (K – 1) * 2
Below is the implementation of the above approach:
C++
#include<bits/stdc++.h>
#include <cmath>
using namespace std;
void FindValue( int N, int K)
{
if ( N % 2 == 0 )
{
N = N + 2 * K;
}
else
{
int i;
for (i = 2; i < sqrt (N) + 1; i++)
{
if (N % i == 0)
break ;
}
N = N + i;
N = N + 2 * ( K - 1 );
}
cout << N << endl;
}
int main()
{
int N = 9;
int K = 4;
FindValue( N, K );
}
|
Java
import java.util.*;
class GFG{
static void FindValue( int N, int K)
{
if ( N % 2 == 0 )
{
N = N + 2 * K;
}
else
{
int i;
for (i = 2 ; i < Math.sqrt(N) + 1 ; i++)
{
if (N % i == 0 )
break ;
}
N = N + i;
N = N + 2 * ( K - 1 );
}
System.out.print(N);
}
public static void main(String args[])
{
int N = 9 ;
int K = 4 ;
FindValue( N, K );
}
}
|
Python3
import math
def FindValue(N, K):
if ( N % 2 = = 0 ):
N = N + 2 * K
else :
for i in range ( 2 , ( int )(math.sqrt(N)) + 1 ):
if ( N % i = = 0 ):
break
N = N + i
N = N + 2 * ( K - 1 )
print (N)
if __name__ = = "__main__" :
N = 9
K = 4
FindValue( N, K )
|
C#
using System;
class GFG{
static void FindValue( int N, int K)
{
if ( N % 2 == 0 )
{
N = N + 2 * K;
}
else
{
int i;
for (i = 2; i < Math.Sqrt(N) + 1; i++)
{
if (N % i == 0)
break ;
}
N = N + i;
N = N + 2 * ( K - 1 );
}
Console.WriteLine(N);
}
public static void Main()
{
int N = 9;
int K = 4;
FindValue( N, K );
}
}
|
Javascript
<script>
function FindValue(N, K)
{
if ( N % 2 == 0 )
{
N = N + 2 * K;
}
else
{
let i;
for (i = 2; i < Math.sqrt(N) + 1; i++)
{
if (N % i == 0)
break ;
}
N = N + i;
N = N + 2 * ( K - 1 );
}
document.write(N + "<br>" );
}
let N = 9;
let K = 4;
FindValue( N, K );
</script>
|
Time complexity: O(?N )
Space Complexity: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...