17 October 2011

Problem 5 - First Attempt

Did not feel like doing thinking about problems 2 through 4, so I skipped straight to problem 5, and am trying a brute force approach with Java, and I think this might come back to bite me in the ass. 


As you can see from the problem, you have to find a number that is evenly divisible by every number from 1 to 20. This number is presumably quite large, because the question says that 2520 is the first number evenly divisible by the number 1 through 10.



My first approach is hanging the system: either the code works and it is just taking a very long time to calculate, or, I am stuck in an infinite loop. Either way, I will have to look over my (crappy) code and figure out what is going on and come up with something better, because although it is simplistic, it also has some fat to be trimmed, most likely in a manner of logic.


PasteBin Link
public class Problem_3 {


public static void main(String[] args) {
int number = 20, answer = 0;

while(answer == 0)
{

if (number % 1 == 0 )
if (number % 2 == 0 )
if (number % 3 == 0 )
if (number % 4 == 0 )
if (number % 5 == 0 )
if (number % 6 == 0 )
if (number % 7 == 0 )
if (number % 8 == 0 )
if (number % 9 == 0 )
if (number % 10 == 0 )
if (number % 11 == 0 )
if (number % 12 == 0 )
if (number % 13 == 0 )
if (number % 14 == 0 )
if (number % 15 == 0 )
if (number % 16 == 0 )
if (number % 17 == 0 )
if (number % 18 == 0 )
if (number % 19 == 0 )
if (number % 20 == 0 )
answer = number;

else
number++;
}

System.out.print("The answer is: " + answer);

}
}



With the code like this for right now, it will take a while to run because the counter number++ is not the fastest thing in the world.


I'll see if I can come up with something better. Mathematica would be a great program to do this in because it crunches huge numbers in no time.

No comments:

Post a Comment