Project Euler — Problem 187

December 23, 2010
By

(This article was first published on YGC » R, and kindly contributed to R-bloggers)

http://projecteuler.net/index.php?section=problems&id=187

A composite is a number containing at least two prime factors. For example, 15 = 3 × 5; 9 = 3 × 3; 12 = 2 × 2 × 3.

There are ten composites below thirty containing precisely two, not necessarily distinct, prime factors: 4, 6, 9, 10, 14, 15, 21, 22, 25, 26.

How many composite integers, n < 10^(8), have precisely two, not necessarily distinct, prime factors?

library(gmp)
bign <- 10^8
n <- 1:floor((bign -1)/2)
p=1:10000
p = p[as.logical(isprime(p))]
for (i in p) {
	n <- n[as.logical(n %% i)]
}
idx <- as.logical(isprime(n))
allp <- c(p,n[idx])
count <- 0
for (i in allp[allp < sqrt(bign)]) {
	count <- count + length(allp[allp < bign/i])
	allp = allp[-1]
}
print(count)

—-
[1] 17427258
user system elapsed
449.67 72.40 522.87

Not fast enough…

Related Posts

To leave a comment for the author, please follow the link and comment on his blog: YGC » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Tags: , ,

Comments are closed.