全部版块 我的主页
论坛 数据科学与人工智能 数据分析与数据科学 R语言论坛
1721 3
2010-10-12
a. Based on the function check.prime, create a new function that can count the number
of primes smaller than the given natural number. Name this new function count.prime.
check.prime是检测给出的X是不是质数,然后count.prime是计算有多少小于X的数是质数,各位,谁知道这个方程该怎么写
b. Let x=c(100*seq(1:500)). Apply the function count.prime to the whole vector of
x and save the counts (output) in y (should be a vector with the same length as x.
De¯ne z=x/log(x). Display y and z.
y=count.prime(x);x=c(100*seq(100:500); z=x/log(x)
c. Plot y versus x. On the same same firguer, add a curve z versus x. Are these two curves
close?
check.prime的指令如下
check.prime<-function(x)
{
if (x<=0 | x%%1!=0)
{out=paste("The input must be a positve integer")}
else {
aa=paste("The input", x, "IS NOT a prime number.")
bb=paste("The input", x, "IS a prime number.")
if (x==1) out=aa
if (x==2 | x==3) out=bb
if (x>=4)
{
m=2; flag=0
while (m<=sqrt(x) & flag==0)
{
if (x%%m==0) flag=1
m=m+1
}
out=ifelse(flag==1, aa, bb)
}
}
out
}


各位大师,知道怎么做的,来帮帮忙!!!
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

全部回复
2010-10-13 00:40:25
count.prime<-function(n){
y<-1:(n-1)
z<-rep(FALSE,n-1)
for (i in y){
z<-check.prime(i)
}
return(sum(z))
}

仅供参考,可进一步优化

1# elysiumking
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

2010-10-13 01:03:22
x=c(100*seq(1:50))
tmp<-as.matrix(x)
y<-apply(tmp,1,count.prime)
plot(x,y)
z<-x/log(x)
lines(x,z,col='BLUE')
注意x改成1:50了,500计算时间太长
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

2010-10-13 09:40:52
谢谢了,大师!!!!
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

相关推荐
栏目导航
热门文章
推荐文章

分享

扫码加好友,拉您进群
各岗位、行业、专业交流群