After experiencing the first two small challenges, you should have a little understanding of R. We continue to push forward. Today's problems are a bit complex. What is complicated is not R, but a Mathematical Concept: Prime Number and quality factor. Any combination of numbers can be decomposed by several prime numbers. This is very important. We will use it to solve the third problem of Project Euler. It is the same as before. You need to tap the following commands on the R console and try your best to find out the result.
# Preparation exercises, learning for loops, creating custom functions, and other functions
For ( N In 1 : 10 ) {
Print ( SQRT ( N ) )
}
X <- C ( 'Hello' , 'World' , 'I' , 'Love' , 'R' )
For ( N In X ) {
Print ( N )
}
X <- Seq ( From = 1 , To = 10 , By = 1 )
Print ( X )
X <- Seq ( From = 1 , To = 10 , By = 2 )
Print ( X)
X <- Seq ( From = 1 , To = 2 , Length. Out = 10 )
Print ( X )
Round ( X )
X> 1.5
All ( X> 1.5 )
Any ( X> 1.5 )
# How to customize a function to calculate the circular area
Myfunc <-Function ( R ) {
Area <- Pi * R ^ 2
Return ( Area )
}
Print ( Myfunc ( 4 ) )
# Calculate the area of four circles with different radius at the same time
R <- C ( 2 , 2 , 4 , 3 )
Sapply ( X = r , Fun = myfunc )
# Project Euler 3
# Find the maximum prime factor of the number 600851475143
# Create a function to determine whether a certain number is a prime number
Findprime <- Function ( X) {
If ( X % in % C ( 2 , 3 , 5 , 7 ) ) Return ( True )
If ( X % 2 = 0 | X = 1 ) Return ( False )
Xsqrt <- Round ( SQRT ( X ) )
Xseq <- Seq ( From = 3 , To = xsqrt , By = 2 )
If ( All ( X % xseq! = 0 ) ) Return ( True )
Else Return ( False )
}
# List the prime numbers from 1 to 100. Check if the function is correct.
X = 1 : 100
X [ Sapply ( X , Findprime ) ]
# Finding the largest Quality Factor
N <-600851475143
For ( I In Seq ( From = 3 , To = Round ( SQRT ( N ) ) , By = 2 ) ) {
If ( Findprime ( I ) & N % I = 0 ) {
N <-N/I
Prime. factor <-I
If ( I> = N )
Break
}
}
Print ( Prime. Factor )
The result is 6857. In this example, in addition to the for loop, we also see the sapply function, which is a very important class of vectorized computing function in the r language. For details about how to calculate the quality number, refer to this article. In this example, realm 4 is used. In fact, based on the nature of the prime factor, this example does not have to establish a function to judge the prime number, but this function will be used later. If you want to use other software to find the quality factor of this number, you can also look at it here.
from data science and R language http://xccds1977.blogspot.com/