Nicholas Hubbard
Code:
public class NaturalNumberSeq {
/**
* Find all natural numbers divisible by either 5 or 3 below 1,000.
* @return Integer result of sum of the relevant natural numbers
*/
public static int findNaturalNumberSum() {
// Initialize the sum variable.
int sum = 0;
// Find all natural numbers, below the given maximum, which are divisible by either 3 or 5.
for (int i = 0; i < 1000; i++) {
if ((i % 3 == 0) || (i % 5 == 0)) {
sum += i;
}
}
// Output the result.
return sum;
}
public static void main(String[] args) {
int result = findNaturalNumberSum();
System.out.println("The sum of all natural numbers below 1,000 which are divisible by 3 or 5 is: " + result);
}
}
Result:
The sum of all natural numbers below 1,000 which are divisible by 3 or 5 is: 234168
Code:
import java.util.ArrayList;
public class FibonacciFunnyness {
public static ArrayList<Integer> fibonacciEvens = new ArrayList<Integer>();
/**
* Find even-value Fibonacci results until a given maximum.
*/
public static int fibonacciEvenSum(int max) {
// Initialize variables.
int first = 0;
int second = 1;
// Find Fibonacci numbers, evens only.
while (first <= max) {
if (first % 2 == 0) {
fibonacciEvens.add(first);
}
int sum = first + second;
first = second;
second = sum;
}
// Print the resulting array.
System.out.println("DEBUG: " + fibonacciEvens);
System.out.println("DEBUG: Number of items: " + fibonacciEvens.size());
// Sum the resulting array.
int finalSum = 0;
for (Integer i : fibonacciEvens) {
finalSum += i;
}
// Return the resulting sum.
return finalSum;
}
public static void main(String[] args) {
int result = fibonacciEvenSum(4000000);
System.out.println("The sum of all even Fibonacci numbers below 4,000,000 is: " + result);
}
}
Result:
DEBUG: [0, 2, 8, 34, 144, 610, 2584, 10946, 46368, 196418, 832040, 3524578]
DEBUG: Number of items: 12
The sum of all even Fibonacci numbers below 4,000,000 is: 4613732