17 October 2011

Problem 1 - Solved

Ah, my first post. Well, this blog will chronicle my experience with Project Euler, a website which posts interesting math problems which you then solve, using logic, programming, or whatever means you can find that don't include just looking up the answer. I came across the site a while ago, but just now starting trying to solve some of the problems by using my new found skills in Java programming. I also know some Mathematica and will use that as well.





Well the first problem on the site was simple enough. I knew that it could easily be solved with a while loop with nested if-statements inside, so I laid down a quick outline, cleared up a minor flaw with the placement of the counter, and got the answer within 10 minutes. Awesome stuff! One problem down now.


Here is my code (pastebin link):



public class Problem_1
{


public static void main(String[] args)
{
// declare ints for number and sum
int number = 0, sum = 0;

// while the counter is less than 1000, stay in loop
while(number < 1000) 

 { 
 // if the new number is divisible by either 3 or 5, add it to total sum 
 if (number % 3 == 0 || number % 5 == 0) 
 sum = sum + number; 
 // count to next number 
 number++; 
 } 
 // print result 
 System.out.print("" + sum); 
 }
 }
This code solves the problem easily, but is 'merely' a brute force attack. The answer can be found with a little logic and algebra, but I would not even know where to start to do that stuff, though some of the people on the Euler Forums had some elegant answers.


I do not use loops or conditionals in Mathematica at all, but once I get a hang of them, it will be easy enough to write some code in that as well.

No comments:

Post a Comment