Find the smallest number which is divisible by all number from 1 to n.
Example 1:
Input : n =3 Output: 6
Approach: Find the LCM of all the number
Java
public class SmallestMultiple {
public static void main(String[] args) {
int n = 3;
int ans = 1;
for (int i = 2; i <= n; i++) {
ans = ans * i / gcd(ans, i);
}
System.out.println(ans);
}
// method for find gcd
private static int gcd(int ans, int i) {
if (i == 0)
return ans;
return gcd(i, ans % i);
}
}
C++
#include <bits/stdc++.h>
using namespace std;
//function to find the gcd of
//two number
int gcd( int a, int b)
{
if(b==0)
return a;
return gcd(b,a%b);
}
int main()
{
int n=3;
int ans=1;
for( int i=2;i<=n;i++)
{
ans=ans*i/gcd(ans,i);
}
cout<<ans<<"\n";
return 0;
}
No comments:
Post a Comment