As the tutorial progresses, the basic syntax is almost the same. To solve a specific problem, you only need to consider the algorithms used to integrate and use these functions and expressions. Today, we have solved the fifth problem of Project Euler. This problem can be solved using a stupid brute force search method. However, the smarter way is to use the idea of qualitative factor decomposition. That is, any sum can be divided into the product of prime numbers. To complete this question, you also need to learn a little matrix and another function similar to the sapply function, apply.
# Preparation exercise
Mat <-matrix (1:12, ncol = 4)
Print (mat)
T (mat)
Colnames (mat) <-c ('one', 'two', 'three ', 'four ')
Rownames (mat) <-c ('A', 'B', 'C ')
Print (mat)
Apply (mat, 1, sum)
Apply (mat, 2, sum)
Sum (apply (mat, 2, sum ))
Prod (apply (mat, 2, sum ))
# The previously established function for determining whether it 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)
}
X = 1:20
Prime <-x [sapply (x, findprime)]
# Euler's question 5: Find the smallest number that can be divisible by 1 to 20.
# Create a factorization Prime Factor Function
Primefactor <-function (x, prime ){
M <-length (prime)
Fac. count <-numeric (m)
Names (fac. count) <-prime
For (I in 1: m ){
Prime. num <-prime [I]
While (x % prime. num = 0 & x! = 1 ){
Fac. count [I] <-fac. count [I] + 1
X = x/prime. num
}
}
Return (fac. count)
}
# The above function is responsible for decomposing a number below 20 into multiple prime numbers.
# Return the number of auto-multiplication times corresponding to each quality factor
Primefactor (18, prime)
# Separate each number from 1 to 20 to form a table
Result <-t (sapply (, primefactor, prime ))
# Calculate the maximum value of each column
Prime. power <-apply (result, 2, max)
Prod (prime ^ prime. power)
The final result is 232792560.
From data science and R language http://xccds1977.blogspot.com/