Friday, January 28, 2011

Naive prime finder

I'm going to try to tackle a few of the first Euler Project tasks. Some of the first ones involve finding prime numbers, so I want to make a generic "is this number prime?" function to handle that.

The basic definition of a prime number is a number that only has two divisors - one and itself - that fit right (no remainder).

Ok well, that's what mod (%) is for. Here is my first run at a program that finds the prime numbers in 1 to 20. I'll explain why this is a naive implementation in a second:



This program is a pretty brute force counter of how many times (index % i) returns 0 (meaning no remainder). Index is the number we want to test, and i loops from 1 to index testing (index % i).

I call this a naive implementation because I know better than to loop through every number up to the index but I want to make it basically work before I "optimize" it.

*EDIT*

I pretty much wrote this in one shot, and it didn't work the first time. Everything was coming up prime. Turned out I fumbled out a = instead of == when checking to see if divisors was 2. "something = something else" is a "true" statement regardless of what both are. "something == something else" is a condition that is true if equal, false if not.

No comments:

Post a Comment