Minimum integer such that it leaves a remainder 1 on dividing with any element from the range [2, N]
Given an integer N, the task is to find the minimum possible integer X such that X % M = 1 for all M from the range [2, N]
Examples:
Input: N = 5
Output: 61
61 % 2 = 1
61 % 3 = 1
61 % 4 = 1
61 % 5 = 1
Input: N = 2
Output: 3
Approach: Find the lcm of all the integers from the range [2, N] and store it in a variable lcm. Now we know that lcm is the smallest number which is divisible by all the elements from the range [2, N] and to make it leave a remainder of 1 on every division, just add 1 to it i.e. lcm + 1 is the required answer.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
long getMinNum( int N)
{
int lcm = 1;
for ( int i = 2; i <= N; i++)
lcm = ((i * lcm) / (__gcd(i, lcm)));
return (lcm + 1);
}
int main()
{
int N = 5;
cout << getMinNum(N);
return 0;
}
|
Java
class GFG {
static long getMinNum( int N)
{
int lcm = 1 ;
for ( int i = 2 ; i <= N; i++)
lcm = ((i * lcm) / (__gcd(i, lcm)));
return (lcm + 1 );
}
static int __gcd( int a, int b)
{
if (b == 0 )
return a;
return __gcd(b, a % b);
}
public static void main(String args[])
{
int N = 5 ;
System.out.println(getMinNum(N));
}
}
|
Python3
from math import gcd
def getMinNum(N) :
lcm = 1 ;
for i in range ( 2 , N + 1 ) :
lcm = ((i * lcm) / / (gcd(i, lcm)));
return (lcm + 1 );
if __name__ = = "__main__" :
N = 5 ;
print (getMinNum(N));
|
C#
using System;
class GFG {
static long getMinNum( int N)
{
int lcm = 1;
for ( int i = 2; i <= N; i++)
lcm = ((i * lcm) / (__gcd(i, lcm)));
return (lcm + 1);
}
static int __gcd( int a, int b)
{
if (b == 0)
return a;
return __gcd(b, a % b);
}
public static void Main()
{
int N = 5;
Console.WriteLine(getMinNum(N));
}
}
|
PHP
<?php
function getMinNum( $N )
{
$lcm = 1;
for ( $i = 2; $i <= $N ; $i ++)
$lcm = (( $i * $lcm ) / (__gcd( $i , $lcm )));
return ( $lcm + 1);
}
function __gcd( $a , $b )
{
if ( $b == 0)
return $a ;
return __gcd( $b , $a % $b );
}
$N = 5;
echo (getMinNum( $N ));
?>
|
Javascript
<script>
function getMinNum(N)
{
var lcm = 1;
for ( var i = 2; i <= N; i++)
lcm = ((i * lcm) / (__gcd(i, lcm)));
return (lcm + 1);
}
function __gcd(a, b)
{
if (b == 0)
return a;
return __gcd(b, a % b);
}
var N = 5;
document.write( getMinNum(N));
</script>
|
Time Complexity: O(N * log(N) )
Auxiliary Space: O(1), as no extra space has been taken.
Last Updated :
31 May, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...