0

I was trying to write an algorithm for given problem:

we are given a set of numbers- {n1,n2,n3,n4,n5......} and we have to check that can we derive a number(Say X) using addition and subtraction by given numbers. X will always be less than all elements of the given set.

Eg.

Set: {2,3,4,6,9}
given number: 1, Result: Yes
9-4-4 =1

Set: {3,4,6,9}
given number: 2, Result: Yes
6-4 = 2

Thanks in advance.

2
  • multiple is OK? so if there is 1, every number is yes. Commented Mar 21, 2011 at 12:20
  • @Dante Jiang : Yes you are right. and i am considering multiple as consecutive number of addition so multiple is also ok. Commented Mar 21, 2011 at 12:26

2 Answers 2

3

Effectively you are looking for the ideal generated by the numbers in your set. The intergers form a principal ideal domain, which means every ideal is generated by a single integer. All you have to do is find this single integer -- say g -- and check whether X can be devided by g. Finding g is also easy -- it's the greatest common divisor of all elements in your set, which can be found using the Euclidean algorithm.

You example sets can generate every integer by addition and substraction, since the can generate 1. For example for the set {3,4,6,9} you have 1=4-3, and any integer n can be written as n times the sum of 4-3.

Sign up to request clarification or add additional context in comments.

1 Comment

Just a small correction: any integer n can be written..., any strictly positive integer. For 0 you use 4-4 and for negatives you sum 3-4. Also +1 to get the math badge. Your answer is a bit theoretical for this forum, but it's a correct one.
0

Assuming, from your first example, that you can use a number multiple times.

The given number must be a multiple of the GCD of your set. That is the only condition. It doesn't matter how big it is.

If you only want an Yes/No answer then it is sufficient to find the GCD. If you also want an expression for the given number the problem can be replaced with finding an expression for the GCD.

GCD = X+Y+..+Z-T-U-...-V

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.