Objective
Your goal (i.e., the requirement for this program) is to find all of the numbers between 1 and 10,000 that have a perfect median. A number n has a perfect median m if the sum of all the integers less than m is equal to the sum of all the integers greater than m, up to and including n. For example, the number n = 8 has the perfect median m = 6, because the sum of the integers from 1 to 5 is equal to the sum of the integers from 7 to 8.
Program Specification
The key to your Java program Median.java is to test each integer to see if it is the perfect median for some sequence of integers. To test an integer m, add all of the integers from 1 to m-1. Then from this sum begin subtracting the integers greater than m. If the result becomes 0, then the last integer you subtracted is the number n that has a perfect median of m. If the result becomes negative, then m is not a perfect median for any number n, so try the next number.
You might make use of the formula 1+2+...+(m-1) = m(m-1)/2
Tuesday, September 14, 2010
Lab07 -- Section 5 -- Perfect Medians
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment