Question

Amazon can sell products in packs of 6,9 and 20. Given a number N, give the algorythm to find its possible or not.

Ex - 21 -- Not Possible 47 (9*3+20) -- Possible

No correct solution

OTHER TIPS

A very simple, but recursive, solution would be

private bool isDiv(int n) {
    if (n < 6) {
        return false;
    } else if (n == 6 || n == 9 || n == 20) {
        Console.Write(n);
        return true;
    } else if (isDiv(n - 6)) {
        Console.Write(" + " + 6);
        return true;
    } else if (isDiv(n - 9)) {
        Console.Write(" + " + 9);
        return true;
    } else if (isDiv(n - 20)) {
        Console.Write(" + " + 20);
        return true;
    }

    return false;
}

But keep in mind that this is not the fastest solution - but it works good for small numbers like the ones in your example

Oh and 21 is quite possible:

2*6 + 9 = 21

A very simple logical solution using C

#include <stdio.h>

int main(){
int x = 6, y=9, z=20,n=26,t1,t2,i;
t1 = n%z;
for(i=0; i<2;i++)
{
if (t1 < y)
{
    t2 = t1%x;
}
else
{
    t2 = t1%y;
    t1 = t2;
    }
}
if (t2 == 0 || t1 == 0)
{
    printf("Yes we can do it");
}
    else
    {
            printf("we cannot do it");
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top