简体   繁体   English

如何从给定数字的所有因子的向量中创建素因子向量?

[英]How do I create a vector of prime factors from a vector of all factors for a given number?

I have generated a list of factors for a given number using a for loop and the append function, which I know is not recommended.我已经使用 for 循环和 append function 生成了给定数字的因子列表,我知道不推荐这样做。

p<-13195
for(i in (p-1):1){
if ((p%%i)==0){
p<-append(p,i)
}
}

I am now trying to report the largest prime factor for this vector, I have used a for loop to print the prime numbers, which is relatively straight forward.我现在正试图报告这个向量的最大素数,我使用了一个 for 循环来打印素数,这是相对简单的。 (I am missing 1, which could easily be added but I am not interested in that value.) (我错过了 1,可以轻松添加,但我对该值不感兴趣。)

for (i in p){
if (sum(i/1:i==i%/%1:i)==2){
print(i)
}
}

However, I want to only print the largest prime factor.但是,我只想打印最大的素数。 I have tried several things to do this but they return errors, for example我已经尝试了几件事来做到这一点,但它们返回错误,例如

for (i in p){
 if (sum(i/1:i==i%/%1:i)==2){
 i<-append(1,i)
}
}

Does not work.不工作。 Plus, I am wary of using the append function.另外,我对使用 append function 持谨慎态度。 I understand that R is not optimised for loops per say, and I am trying to develop my skills as a programmer so I am looking for alternatives to loops, but I don't mind what the solution is.我知道 R 没有针对循环进行优化,我正在努力发展我作为程序员的技能,所以我正在寻找循环的替代方案,但我不介意解决方案是什么。 Ideally I'd like a vector of primes so that I could easily apply理想情况下,我想要一个素数向量,以便我可以轻松应用

max()

Thank you.谢谢你。

n<-c()
for (i in p){
    if (sum(i/1:i==i%/%1:i)==2){
        n=c(n,i)
    }
}

max<-max(n)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM