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