I have a set of given integers:
A[] = { 2, 3, 4, 5, 6, 7, 8, 10, 15, 20, 25, 30, 40, 50, 100, 500 }
-
I want to check if a given integer
Tcan be written as a multiple of the numbers inA[];
EDIT CLARIFICATION:
any number in A[] can be used.If used can be used only one time.
EX 60 is a valid T.60=30*2.
AlSO 90 is valid . 90=3*5*6 -
Check which numbers can form that integer
T. - Also return the 2 closest integers to the given
T(that can be written that way) if the numberTcannot be written as a multiple of that numbers.
Parts 2 and 3, I think I can sort out of my own if someone helps me with part 1.
I know this is an algorithmic question or even a mathematical one but if anyone can help, please do.
NOT HOMEWORK. SEE COMMENT BELOW.
#
SOLUTION.
TY VERY MUCH FOR ALL ANSWERS.1 answer particulary (but the author choose to remove it and i don’t know really why since it was correct.)
Ty author (don’t remember your name.)
#
Solution Code with a twist(The author’s algorithm used multiple times one multiplier.This one uses multiplier only 1 time)
int oldT = 0;
HashMap<Integer, Boolean> used = new HashMap<Integer, Boolean>();
while (T != 1 && T != -1) {
oldT = T;
for (int multiple : A) {
if (!used.containsKey(multiple)) {
if (T % multiple == 0) {
T = T / multiple;
used.put(multiple, true);
}
}
}
if (oldT == T)
return false;
}
return true;
If T is not very big (say, < 10^7), this is straight DP.
That’s assuming every multiplier can be used only once.
Now, you can find decomposition of T if you have another array b[i] storing which multiplier was used to achieve i.
There’s a lot of online content to get familiar with dynamic programming, if you have little time. It should give you idea how to approach such problems. For example, this one seems not bad
http://www.topcoder.com/tc?module=Static&d1=tutorials&d2=dynProg