PRATIAN Interview Question
Java DevelopersCountry: India
Interview Type: Written Test
What you're looking for is basically LCM(least common multiplier) of 2,3,4,5,6,7 multiplied by 1,2 and 4. The standard implementation of LCM would be with using LCM(a,b) = |a*b|/GCD(a,b) and using Euclidean algorithm for calculating GCD(a,b).
Here's what I sketched:
public static void main(String[] args){
int[] divisors = new int[]{2,3,4,5,6,7};
int[] multipliers = new int[]{1,2,4};
displayMultiples(divisors, multipliers);
}
static void displayMultiples(int[] divisors, int[] multipliers){
int lcm = lcm(divisors);
for(int i = 0; i < multipliers.length; i++){
System.out.print(multipliers[i]*lcm + " ");
}
System.out.println();
}
// least common multiple
private static int lcm(int[] array){
int multiple = 1;
int gcdFactor = 1;
for (int i = 0; i<array.length; i++) {
multiple *= array[i];
Set<Integer> gcdSet= new HashSet<Integer>();
for(int j = i+1; j < array.length; j++){
gcdSet.add(gcd(array[i],array[j]));
}
for(int k : gcdSet)
gcdFactor*= k;
}
return Math.abs(multiple)/gcdFactor;
}
// greatest common divisor
private static int gcd(int a,int b){
if(a < b){
int temp = b;
b = a;
a = temp;
}
int r = a%b;
while(r != 0){
a = b;
b = r;
r = a%b;
}
return b;
}
public static void main(String[] args){
int[] divisors = new int[]{2,3,4,5,6,7};
int[] multipliers = new int[]{1,2,4};
displayMultiples(divisors, multipliers);
}
static void displayMultiples(int[] divisors, int[] multipliers){
int lcm = lcm(divisors);
for(int i = 0; i < multipliers.length; i++){
System.out.print(multipliers[i]*lcm + " ");
}
System.out.println();
}
// least common multiple
private static int lcm(int[] array){
int multiple = 1;
int gcdFactor = 1;
for (int i = 0; i<array.length; i++) {
multiple *= array[i];
Set<Integer> gcdSet= new HashSet<Integer>();
for(int j = i+1; j < array.length; j++){
gcdSet.add(gcd(array[i],array[j]));
}
for(int k : gcdSet)
gcdFactor*= k;
}
return Math.abs(multiple)/gcdFactor;
}
// greatest common divisor
private static int gcd(int a,int b){
if(a < b){
int temp = b;
b = a;
a = temp;
}
int r = a%b;
while(r != 0){
a = b;
b = r;
r = a%b;
}
return b;
}
/* Write a program to display 1st, 2nd and 4th multiples of 7which also gives the remainder 0 (ZERO) when it divided by 2,3,4,5 and 6. */
#include<bits/stdc++.h>
using namespace std;
int main()
{
int i,count=1;
for(i=1;;i++)
{
//lcm of 2,3,4,5 and 6 =60.
if(60*i%7==0)
{
if(count==1 || count==2 || count==4)
cout<<60*i<<endl;
count++;
if(count > 4)
break;
}
}
return 0;
}
public class Multiplesof7 {
- KNSManasa December 06, 2016public static void main(String[] args) {
int k = 0;
int i=7;
while ( k< 5 && i >= 7) {
if ((i % 2 == 0) && (i % 3 == 0) && (i % 4 == 0) && (i % 5 == 0) && (i % 6 == 0)) {
k++;
if(k<3 ||k==4){
System.out.println(k + " "+"Number " + i);
}
}
i+=7;
}
}
}