Monthly Archives: August 2015

Euler 2 – C# (Brute force)

Question:
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

Logic:
To represent the Fibonacci sequence in programming we assign the first and second numbers (1 and 2) and a sum representing the next number in the sequence
int fib1 = 1;
int fib2 = 2;
int fib3 = 0; //this will be fib1 + fib2
int total = 0;

Now we must set a limit of under 4 million in the sequence and write the sequence logic in a while loop
while(fib3 < 4000000) { //fib3 returns the highest value in the sequence
if (fib2 % 2 == 0) { //if condition searches for even numbers in the sequence
total += fib2; //total is added by fib2 every iteration that passes the if statement
}
fib3 = fib1 + fib2;
fib1 = fib2;
fib2 = fib3;
}
Console.WriteLine(total); //Answer is 4613732

Euler 1 – Java

Brute force approach

Question: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.

Logic: The first part of the problem asks us to find the multiples of 3 & 5 under 1000. For this, we write a simple for loop starting from 3 and ending before 1000.
for(int x = 3; x < 1000; x++){}

Next we select all the values that are divisible by 3 and 5. We use the if statement and the %(modulus) operand to find the the remainder of each increment of x.
if(x % 3 == 0 || x % 5 == 0){}

Finally we take every value that passes the if check and add it upon itself.
int total = 0;
...
total += x;

Code:
//generate for loop going to 1000 starting from 3 and incrementing by 1
int total = 0;
for(int x=3; x<1000; x++){
//filter by multiples of 3 and 5
if(x%3 == 0 || x%5 == 0){
//add numbers filtered by if statement
total += x;
}
}
System.out.println("total sum is:" +total); //answer is 233168