简体   繁体   中英

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.

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. (I am missing 1, which could easily be added but I am not interested in that value.)

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. 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. 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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