20 October 2011

Problem 5 - Solution

After combing over my code, trying to figure out where the small logic error in it was, I got a small idea to change the location of one of the if statements, putting it inside one of the while loop above it. I then tested this to find the Least Common Denominator for all numbers from 1 to 10, and it worked!

So I made the same changes in the code to make it find the Least Common Denominator for all integers from 1 to 20, and set it running. Of course, it still took a long time, but this time it worked, and I got the right answer!

Here is my final code:
PasteBin Link

public class Problem_5
{
public static void main(String[] args)
{
// num is what will look for answer
// answer will be set to num when found
// n is for recursively dividing
int count = 20, ans = 0, n = 2;

// while the answer has not been found
// continue searching
while (ans == 0)
{
//System.out.println("Entered loop");
n = 2;
// set dividor back to 2 and start again
while (n <= 20) 

 { 
 if ((count%n) == 0) 
 { System.out.println("" + count + " " + n); n++; 
 } 
 else n = 21; 
 // if num can be modded by 20 
 // and if n gets to 20 
 // then this must be the answer 
 // otherwise the while loop 
 // would have stopped 
 if ((count % 20 == 0) && (n == 20)) 
 { 
 ans = count; 
 System.out.println("The answer is: " + ans); 
 } 
 } 
 count++; 
 } } }


Now comes optimization. Since the answer has to be divisible by 2 (even), I could modify the counter to add 2 rather than 1. Also, I could test for divisibility by the number of 10 through 20, or maybe 5 through 20, which will take some of the steps out of it, but I do not think this would be mathematically rigorous, though it may still work.

No comments:

Post a Comment