List all factors and find primes

This function lists all factors of a number:

factors <- function(n) {
	p <- 1:floor(n/2)
	p <- c(p,n)
	d <- n/p
	return(d[d == round(d,0)])
}

And then this uses the ‘factors’ to list all prime numbers between ‘min’ and ‘max’. This is just for fun – it doesn’t work with large numbers.

prime <- function (max, min = 2) {
	t <- min
	vec <- NULL
	while (t <= max) {
		if (length(factors(t)) == 2) {
			vec <- c(vec, t)
		}
		t <- t + 1
	}
	return(vec)
}
Advertisements

One thought on “List all factors and find primes

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s