Question :
An
integer is defined to be an even
subset of another integer n if every even factor of m is also a factor of n. For example 18 is an even
subset of 12 because the even factors of 18 are 2 and 6 and these are both
factors of 12. But 18 is not an even subset of 32 because 6 is not a factor of
32.
Write
a function with signature int
isEvenSubset(int m, int n) that
returns 1 if m is an even subset of n, otherwise it returns 0.
Solution :
public static int
isEvenSubSet(int m, int n)
{
int result
= 0;
for (int i = 2; i < m; i++)
{
if (m % i
== 0 && i%2==0)
{
for (int j = 2; j < n; j++)
{
if (n % j == 0)
{
if (i == j)
{
result = 1;
}
else
{
result = 0;
}
}
}
}
}
return result;
}
This comment has been removed by the author.
ReplyDeleteThis code is correct
ReplyDelete// O(N) Time | O(1) Space
public static int isEvenSubset(int m, int n) {
int result = 0;
for (int i = 2; i <= m / 2; i += 2) {
if (m % i == 0) {
if (n % i == 0) {
result = 1;
} else {
result = 0;
break;
}
}
}
return result;
}
This comment has been removed by the author.
ReplyDeletepublic static int isEvenSubset(int m, int n){
ReplyDeletefor(int i=2;i<m;i+= 2){
if(m%i == 0 && n%i != 0){
return 0;
}
}
return 1;
}