Tuesday, October 14, 2008

http://projecteuler.net Problem 2

This problem asked to sum up all even Fibanacci number up to 4,000,000. This code executed in .02 seconds


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ProjectEularProb2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
DateTime dtstart = DateTime.Now;
List numb = new List();
List lastNumb = new List();
int x = 1;
int y=0;
//numb.Add(x);
listBox1.Items.Add(x);
lastNumb.Add(1);

do
{
y = lastNumb.Last();
x = x + y;
listBox1.Items.Add(x);
if (IsEven(x).Equals(true))
{
numb.Add(x);
listBox2.Items.Add(x);
}

lastNumb.Add(x - y);
}
while (x <= 4000000);
textBox1.Text = numb.Sum().ToString();
DateTime dtend = DateTime.Now;
label3.Text = "Program took " + dtend.Subtract(dtstart) + " to complete";
}
private bool IsEven(int x)
{
int y = x % 2;
if (y==0)
{
return true;
}
else
{
return false;
}
}
}
}

No comments: