Level Problems 1
Multiples of 3 or 5
If we list all natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all multiples of 3 or 5 below 1000.
R Code
multiplos <- function(numMax){
num <- seq_len(numMax-1)
test <- apply(rbind(num %% 3, num %% 5), 2, min)
return(sum(num[test == 0]))
}
multiplos(10)
> 23
multiplos(1000)
> 233168
multiplos <- function(numMax, mult){
num <- seq_len(numMax-1)
vecMult <- lapply(mult , function(div) num %% div)
matMult <- do.call(rbind, vecMult)
test <- apply(matMult, 2, min)
return(sum(num[test == 0]))
}
multiplos(10, c(3,5))
> 23
multiplos(1000, c(3,5))
> 233168
Even Fibonacci numbers
Each new term in the Fibonacci sequence is generated by adding the two previous terms. Starting with 1 and 2, the first 10. The terms will be:
$$1,2,3,5,8,13, 21, 34, 55, 89, \dots$$When considering terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even terms.
R Code
fib_tbl <- c(0, 1, rep(NA, 23))
fibMemory <- function(n){
stopifnot(n > 0)
if(!is.na(fib_tbl[n]))
fib_tbl[n]
else {
fib_tbl[n - 1] <<- fibMemory(n - 1)
fib_tbl[n - 2] <<- fibMemory(n - 2)
fib_tbl[n - 1] + fib_tbl[n - 2]
}
}
somPar1 <- function(num) {
seqFib <- unlist(lapply(seq_len(num), function(val) fibMemory(val)))
seqFib <- seqFib[!is.na(seqFib)]
seqFib <- seqFib[!is.infinite(seqFib)]
resp <- seqFib[seqFib %% 2 == 0]
resp <- resp[resp < (4*10^6)]
newresp <- cumsum(resp)
return(tail(newresp,1))
}
somPar1(10)
> 44
somPar1(4*10^3)
> 4613732
Largest prime factor
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143?
R Code
divis <- function(num){
divnum <- NULL
count <- 2
repeat{
if(num == 1)
break
if(num %% count == 0){
num <- num/count
divnum <- c(divnum, count)
print(num)
}
count <- count + 1
}
print(divnum)
return(max (divnum))
}
divis(13195)
> 29
divis(600851475143)
> 6857
Largest palindrome product
A palindromic number is read the same both ways. The largest palindrome made from the product of two 2 digit numbers
$$ 9009 = 91 \times 99$$Find the largest palindrome made from the product of two 3 digit numbers.
R Code
geraRev <- function(num)
return(as.numeric(
paste(rev(unlist(strsplit(as.character(num),"",fixed=TRUE))), collapse="")))
calcProdMaxPalindromo <- function(numTeste){
# numTeste <- 900:999
## encontra possibilidades de capicua (div 11)
possible <- numTeste[numTeste %% 11 ==0]
## cria matrix com numeros de teste, possibilidades e multiplicacao das 2 primeiras colunas
mat <- lapply(possible, function(p) cbind(numTeste, p, numTeste * p))
mat <- do.call(rbind, mat)
prodNum <- mat[,3]
## reverte os algarismos
revnum1 <- unlist(lapply(prodNum, function(i) geraRev(i)))
## vector booleano de capicuas
checkPalin <- prodNum == revnum1
## filtra o produtos de capicuas
matPoss <- mat[checkPalin, ]
## pega maior produto
return(max(matPoss[,3]))
}
calcProdMaxPalindromo(900:999)
> 906609
Smallest multiple
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all numbers from 1 to 20?
R Code
## maximo divisor comum
mdc <- function(a, b){
if( b == 0)
return(a)
return(mdc(b, (a %% b)))
}
## mínimo multiplo comum
mmc <- function(numeros){
m <- 1
for(n in numeros)
m <- m * n / mdc(m, n)
return(m)
}
mmc(1:10)
> 2520
mmc(1:11)
> 27720
mmc(1:13)
> 360360
mmc(1:20)
> 232792560
Square Sum Difference
The sum of the squares of the first ten natural numbers is,
$$1^2+ 2^2 + \dots + 10^2 = 385$$The square of the sum of the first ten natural numbers is,
$$(1+2+\dots + 10)^2 = 55^2 = 3025$$Therefore, the difference between the sum of the squares of the first ten natural numbers and the square of the sum is
$$3025-385=2640$$Find the difference between the sum of the squares of the first hundred natural numbers and the square of the sum.
R Code
vec <- 1:100
difsomaquad <- function(valmax) sum(seq(valmax))^2 - sum(seq(valmax)^2)
difsomaquad(10)
> 2640
difsomaquad(100)
> 25164150
10001st cousin
When listing the first six prime numbers:
$$2,3,5,7,11,13$$we can see that the sixth prime is 13.
What is the 10001st prime number?
R Code
primeNumbers <- function(n) {
if (n < 2)
stop("Input number should be at least 2.")
x <- seq(2, n)
primeNums <- c()
for (i in seq(2, n)) {
if (any(x == i)) {
primeNums <- c(primeNums, i)
x <- c(x[(x %% i) != 0], i)
}
}
return(primeNums)
}
numprime <- primeNumbers(200000)
tail(numprime[1:6],1)
> 13
tail(numprime[1:10001],1)
> 104743
Biggest product in a series
The four adjacent digits in the thousandth digit number that has the largest product is
$$9\times 9\times 8\times 9 = 5832$$73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113 62229893423380308135336276614282806444486645238749 30358907296290491560440772390713810515859307960866 70172427121883998797908792274921901699720888093776 65727333001053367881220235421809751254540594752243 52584907711670556013604839586446706324415722155397 53697817977846174064955149290862569321978468622482 83972241375657056057490261407972968652414535100474 82166370484403199890008895243450658541227588666881 16427171479924442928230863465674813919123162824586 17866458359124566529476545682848912883142607690042 24219022671055626321111109370544217506941658960408 07198403850962455444362981230987879927244284909188 84580156166097919133875499200524063689912560717606 05886116467109405077541002256983155200055935729725 71636269561882670428252483600823257530420752963450
Find the thirteen adjacent digits in the thousandth digit number that has the best product. What is the value of this product?
R Code
str <- "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450"
seqN <- 13
getMaxProd <- function(str, seqN){
allNum <- as.numeric(unlist(strsplit(str, split = "")))
allSeq <- lapply(1:(length(allNum) - seqN + 1), function(i) allNum[i:(i + seqN - 1)])
matSeq <- do.call(rbind, allSeq)
respProd <- cbind.data.frame(matSeq, prod = apply(matSeq, 1, prod))
return(max(respProd[,"prod"]))
}
getMaxProd(str, 4)
> 5832
getMaxProd(str, 13)
> 23514624000
Special Pythagorean suit
A Pythagorean triple is a set of three natural numbers with $a< b< c$, for which:
$$a^2+ b^2 = c^2$$For example,
$$3^2+ 4^2 = 9 + 16 = 25 = 5^2$$There is exactly one Pythagorean suit for which
$$a+b+c=1000$$Find the product
$$abc$$
R Code
mdc <- function(a, b){
if(b == 0)
return(a)
return(mdc(b, (a %% b)))
}
## Pythagorean Triple Condition
## Euclides Equation
## if m > n and mdc(m, n) = 1 with m, n integer
## a = 2*m*n, b = m^2 - n^2, c = m^2 + n^2
prodPythagoreanTriple <- function(sumTarget) {
n <- 1
m <- 2
repeat{
if(mdc(m, n) == 1){
a <- 2*m*n
b <- m^2 - n^2
c <- m^2 + n^2
k <- sumTarget/sum(c(a, b, c))
if(sumTarget %% k == 0){
a <- k * a
b <- k * b
c <- k * c
break
}
}
m <- m + 1
}
return(a * b * c)
}
prodPythagoreanTriple(1000)
> 31875000
Sum of primes
The sum of the primes below fr 10 is:
$$2+3+5+7=17$$Find the sum of all primes below two million.
R Code
primeNumbers <- function(n) {
if (n < 2)
stop("Input number should be at least 2.")
x <- seq(2, n)
primeNums <- c()
for (i in seq(2, n)) {
if (any(x == i)) {
primeNums <- c(primeNums, i)
x <- c(x[(x %% i) != 0], i)
}
}
return(primeNums)
}
numprime <- primeNumbers(2000001)
sumPrime <- function(target, numprime) sum(numprime[numprime < target])
sumPrime(10, numprime)
> 17
sumPrime(2000000, numprime)
> 142913828922
Largest product in a grid
In the grid of 20 x 20 below, four numbers along a diagonal line have been marked in red.
08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48
R Code
productDirection <- function(i, j, mat, direction) {
n <- nrow(mat)
if (direction == "horizontal" && j <= n - 3)
return(prod(mat[i, j + c(0,1,2,3)]))
if (direction == "vertical" && i <= n - 3)
return(prod(mat[i+ c(0,1,2,3), j ]))
if (direction == "diag_dr" && i <= n - 3 && j <= n - 3)
return(mat[i, j] * mat[i+1, j+1] * mat[i+2, j+2] * mat[i+3, j+3])
if (direction == "diag_dl" && i <= n - 3 && j >= 4)
return(mat[i, j] * mat[i+1, j-1] * mat[i+2, j-2] * mat[i+3, j-3])
if (direction == "vertical_up" && i >= 4)
return(prod(mat[i- c(0,1,2,3), j ]))
return(0)
}
greaterProduct <- function(mat) {
n <- nrow(mat)
dir <- c("horizontal", "vertical", "diag_dr", "diag_dl", "vertical_up")
index <- expand.grid(i = 1:n, j = 1:n, direction = dir)
prod <- mapply(function(i, j, direction)
productDirection(i, j, mat, direction),
index[, "i"],
index[, "j"],
index[, "direction"])
return(max(prod))
}
greaterProduct(mat)
> 70600674
Largest divisible triangular number
The sequence of triangular numbers is generated by adding the natural numbers. Therefore, the seventh number in the triangle would be
$$1+2+3+4+5+6+7=28$$The first ten terms would be:
$$1,3,6,10,15,21,28,36,45,55,\dots$$
We can see that 28 is the first triangle number to have more than five divisors. What is the value of the first number in the triangle to have more than five hundred divisors?
R Code
divisors <- function(x){
# Vector of numberes to test against
y <- seq_len(x)
# Modulo division. If remainder is 0 that number is a divisor of x so return it
return(y[ x%%y == 0 ])
}
# Função para calcular o número de divisores
divisorNumb <- function(n) {
count <- 0
for (i in 1:sqrt(n)) {
if (n %% i == 0) {
if (i * i == n)
count <- count + 1
else
count <- count + 2
}
}
return(count)
}
# Função para encontrar o primeiro número triangular com mais de 500 divisores
getTriangleNumberLimit <- function(limDiv) {
triangleNum <- 0
i <- 1
repeat {
triangleNum <- triangleNum + i
if (divisorNumb(triangleNum) > limDiv)
return(triangleNum)
i <- i + 1
}
}
# Encontrar o primeiro número triangular com mais de 500 divisores
resultado <- getTriangleNumberLimit(500)
print(resultado)
> 76576500
Version 2
R Code
# Função para gerar números primos até um certo limite usando o Crivo de Eratóstenes
crivo_eratostenes <- function(limite) {
primos <- rep(TRUE, limite)
primos[1] <- FALSE # 1 não é primo
for (i in 2:sqrt(limite)) {
if (primos[i]) {
primos[seq(i*i, limite, by=i)] <- FALSE
}
}
return(which(primos))
}
# Função para fatorar um número inteiro em seus fatores primos
fatoracao_prima <- function(n) {
if (n <= 1)
stop("O número deve ser maior que 1.")
fatores <- integer() # Vetor para armazenar os fatores primos
# Obter todos os primos até a raiz quadrada de n
limite <- floor(sqrt(n))
primos <- crivo_eratostenes(limite)
for (divisor in primos) {
while (n %% divisor == 0) {
fatores <- c(fatores, divisor)
n <- n / divisor
}
}
# Se n é um número primo maior que a raiz quadrada de n
if (n > 1)
fatores <- c(fatores, n)
return(fatores)
}
# Função para calcular o número de divisores
divisorNumb <- function(n) {
if (n <= 0)
stop("O número deve ser maior que 0.")
# Obter a fatoração prima do número
fatores <- fatoracao_prima(n)
# Contar a multiplicidade de cada fator primo
tabela_fatores <- table(fatores)
# Calcular o número de divisores a partir das multiplicidades
numero_divisores <- prod(tabela_fatores + 1)
return(numero_divisores)
}
# Função para encontrar o primeiro número triangular com mais de 500 divisores
getTriangleNumberLimit <- function(limDiv) {
triangleNum <- 0
i <- 1
repeat {
triangleNum <- triangleNum + i
if (divisorNumb(triangleNum) > limDiv)
return(triangleNum)
i <- i + 1
}
}
# Encontrar o primeiro número triangular com mais de 500 divisores
resultado <- getTriangleNumberLimit(500)
print(resultado)
> 76576500
Big Sum
Calculate the first ten digits of the sum of the next hundred 50 digit numbers.
46376937677490009712648124896970078050417018260538
74324986199524741059474233309513058123726617309629
91942213363574161572522430563301811072406154908250
23067588207539346171171980310421047513778063246676
89261670696623633820136378418383684178734361726757
28112879812849979408065481931592621691275889832738
44274228917432520321923589422876796487670272189318
47451445736001306439091167216856844588711603153276
70386486105843025439939619828917593665686757934951
62176457141856560629502157223196586755079324193331
64906352462741904929101432445813822663347944758178
92575867718337217661963751590579239728245598838407
58203565325359399008402633568948830189458628227828
80181199384826282014278194139940567587151170094390
35398664372827112653829987240784473053190104293586
86515506006295864861532075273371959191420517255829
71693888707715466499115593487603532921714970056938
54370070576826684624621495650076471787294438377604
53282654108756828443191190634694037855217779295145
36123272525000296071075082563815656710885258350721
45876576172410976447339110607218265236877223636045
17423706905851860660448207621209813287860733969412
81142660418086830619328460811191061556940512689692
51934325451728388641918047049293215058642563049483
62467221648435076201727918039944693004732956340691
15732444386908125794514089057706229429197107928209
55037687525678773091862540744969844508330393682126
18336384825330154686196124348767681297534375946515
80386287592878490201521685554828717201219257766954
78182833757993103614740356856449095527097864797581
16726320100436897842553539920931837441497806860984
48403098129077791799088218795327364475675590848030
87086987551392711854517078544161852424320693150332
59959406895756536782107074926966537676326235447210
69793950679652694742597709739166693763042633987085
41052684708299085211399427365734116182760315001271
65378607361501080857009149939512557028198746004375
35829035317434717326932123578154982629742552737307
94953759765105305946966067683156574377167401875275
88902802571733229619176668713819931811048770190271
25267680276078003013678680992525463401061632866526
36270218540497705585629946580636237993140746255962
24074486908231174977792365466257246923322810917141
91430288197103288597806669760892938638285025333403
34413065578016127815921815005561868836468420090470
23053081172816430487623791969842487255036638784583
11487696932154902810424020138335124462181441773470
63783299490636259666498587618221225225512486764533
67720186971698544312419572409913959008952310058822
95548255300263520781532296796249481641953868218774
76085327132285723110424803456124867697064507995236
37774242535411291684276865538926205024910326572967
23701913275725675285653248258265463092207058596522
29798860272258331913126375147341994889534765745501
18495701454879288984856827726077713721403798879715
38298203783031473527721580348144513491373226651381
34829543829199918180278916522431027392251122869539
40957953066405232632538044100059654939159879593635
29746152185502371307642255121183693803580388584903
41698116222072977186158236678424689157993532961922
62467957194401269043877107275048102390895523597457
23189706772547915061505504953922979530901129967519
86188088225875314529584099251203829009407770775672
11306739708304724483816533873502340845647058077308
82959174767140363198008187129011875491310547126581
97623331044818386269515456334926366572897563400500
42846280183517070527831839425882145521227251250327
55121603546981200581762165212827652751691296897789
32238195734329339946437501907836945765883352399886
75506164965184775180738168837861091527357929701337
62177842752192623401942399639168044983993173312731
32924185707147349566916674687634660915035914677504
99518671430235219628894890102423325116913619626622
73267460800591547471830798392868535206946944540724
76841822524674417161514036427982273348055556214818
97142617910342598647204516893989422179826088076852
87783646182799346313767754307809363333018982642090
10848802521674670883215120185883543223812876952786
71329612474782464538636993009049310363619763878039
62184073572399794223406235393808339651327408011116
66627891981488087797941876876144230030984490851411
60661826293682836764744779239180335110989069790714
85786944089552990653640447425576083659976645795096
66024396409905389607120198219976047599490197230297
64913982680032973156037120041377903785566085089252
16730939319872750275468906903707539413042652315011
94809377245048795150954100921645863754710598436791
78639167021187492431995700641917969777599028300699
15368713711936614952811305876380278410754449733078
40789923115535562561142322423255033685442488917353
44889911501440648020369068063960672322193204149535
41503128880339536053299340368006977710650566631954
81234880673210146739058568557934581403627822703280
82616570773948327592232845941706525094512325230608
22918802058777319719839450180888072429661980811197
77158542502016545090413245809786882778948721859617
72107838435069186155435662884062257473692284509516
20849603980134001723930671666823555245252804609722
53503534226472524250874054075591789781264330331690
R Code
x <- c("37107287533902102798797998220837590246510135740250","46376937677490009712648124896970078050417018260538",
"74324986199524741059474233309513058123726617309629","91942213363574161572522430563301811072406154908250",
"23067588207539346171171980310421047513778063246676","89261670696623633820136378418383684178734361726757",
"28112879812849979408065481931592621691275889832738","44274228917432520321923589422876796487670272189318")
y <- c("47451445736001306439091167216856844588711603153276","70386486105843025439939619828917593665686757934951",
"62176457141856560629502157223196586755079324193331","64906352462741904929101432445813822663347944758178",
"92575867718337217661963751590579239728245598838407","58203565325359399008402633568948830189458628227828",
"80181199384826282014278194139940567587151170094390","35398664372827112653829987240784473053190104293586",
"86515506006295864861532075273371959191420517255829","71693888707715466499115593487603532921714970056938")
z <- c("54370070576826684624621495650076471787294438377604","53282654108756828443191190634694037855217779295145",
"36123272525000296071075082563815656710885258350721","45876576172410976447339110607218265236877223636045",
"17423706905851860660448207621209813287860733969412","81142660418086830619328460811191061556940512689692",
"51934325451728388641918047049293215058642563049483","62467221648435076201727918039944693004732956340691",
"15732444386908125794514089057706229429197107928209","55037687525678773091862540744969844508330393682126",
"18336384825330154686196124348767681297534375946515","80386287592878490201521685554828717201219257766954",
"78182833757993103614740356856449095527097864797581","16726320100436897842553539920931837441497806860984",
"48403098129077791799088218795327364475675590848030","87086987551392711854517078544161852424320693150332",
"59959406895756536782107074926966537676326235447210","69793950679652694742597709739166693763042633987085",
"41052684708299085211399427365734116182760315001271","65378607361501080857009149939512557028198746004375")
w <- c("35829035317434717326932123578154982629742552737307","94953759765105305946966067683156574377167401875275",
"88902802571733229619176668713819931811048770190271","25267680276078003013678680992525463401061632866526",
"36270218540497705585629946580636237993140746255962","24074486908231174977792365466257246923322810917141",
"91430288197103288597806669760892938638285025333403","34413065578016127815921815005561868836468420090470",
"23053081172816430487623791969842487255036638784583","11487696932154902810424020138335124462181441773470",
"63783299490636259666498587618221225225512486764533","67720186971698544312419572409913959008952310058822",
"95548255300263520781532296796249481641953868218774","76085327132285723110424803456124867697064507995236",
"37774242535411291684276865538926205024910326572967","23701913275725675285653248258265463092207058596522",
"29798860272258331913126375147341994889534765745501","18495701454879288984856827726077713721403798879715",
"38298203783031473527721580348144513491373226651381","34829543829199918180278916522431027392251122869539",
"40957953066405232632538044100059654939159879593635","29746152185502371307642255121183693803580388584903",
"41698116222072977186158236678424689157993532961922","62467957194401269043877107275048102390895523597457",
"23189706772547915061505504953922979530901129967519","86188088225875314529584099251203829009407770775672",
"11306739708304724483816533873502340845647058077308","82959174767140363198008187129011875491310547126581",
"97623331044818386269515456334926366572897563400500","42846280183517070527831839425882145521227251250327",
"55121603546981200581762165212827652751691296897789","32238195734329339946437501907836945765883352399886",
"75506164965184775180738168837861091527357929701337","62177842752192623401942399639168044983993173312731",
"32924185707147349566916674687634660915035914677504","99518671430235219628894890102423325116913619626622",
"73267460800591547471830798392868535206946944540724","76841822524674417161514036427982273348055556214818",
"97142617910342598647204516893989422179826088076852","87783646182799346313767754307809363333018982642090",
"10848802521674670883215120185883543223812876952786","71329612474782464538636993009049310363619763878039",
"62184073572399794223406235393808339651327408011116","66627891981488087797941876876144230030984490851411",
"60661826293682836764744779239180335110989069790714","85786944089552990653640447425576083659976645795096",
"66024396409905389607120198219976047599490197230297","64913982680032973156037120041377903785566085089252",
"16730939319872750275468906903707539413042652315011","94809377245048795150954100921645863754710598436791",
"78639167021187492431995700641917969777599028300699","15368713711936614952811305876380278410754449733078",
"40789923115535562561142322423255033685442488917353","44889911501440648020369068063960672322193204149535",
"41503128880339536053299340368006977710650566631954","81234880673210146739058568557934581403627822703280",
"82616570773948327592232845941706525094512325230608","22918802058777319719839450180888072429661980811197",
"77158542502016545090413245809786882778948721859617","72107838435069186155435662884062257473692284509516",
"20849603980134001723930671666823555245252804609722","53503534226472524250874054075591789781264330331690")
numbers = as.numeric(c(x,y, z,w))
totalSum <- sum(numbers)
firstTenDigits <- substr(as.character(totalSum), 1, 10)
> 5537376230
Collatz Long Sequence
The following iterative sequence is defined for the set of positive integers:
$$n \rightarrow \frac{n}{2} \quad \text{n par}$$$$n \rightarrow 3n+1 \quad \text{n ímpar}$$
Using the rule above and starting with 13 , we generate the following sequence:
$$13 \rightarrow 40\rightarrow 20 \rightarrow 10 \rightarrow 5 \rightarrow 16 \rightarrow 8 \rightarrow 4 \rightarrow 2 \rightarrow 1$$It can be seen that this sequence (starting at 13 and ending at 1) contains 10 terms. Although it has not yet been proven (Collatz Problem), it is believed that all starting numbers end in 1.
Which starting number, below a million, produces the longest chain?
NOTE: Once the chain begins, deadlines can exceed a million.
R Code
# Função para calcular o comprimento da sequência de Collatz para um determinado número
collatzLength <- function(n) {
collatzLen <- 1
repeat {
if (n %% 2 == 0)
n <- n / 2
else
n <- 3 * n + 1
collatzLen <- collatzLen + 1
if(n == 1) break
}
return(collatzLen)
}
# Encontre o número abaixo de um milhão que produz a cadeia mais longa
longestChain <- function(limit) {
max_length <- 0
number_with_longest_chain <- 0
for (i in 1:(limit - 1)) {
len <- collatzLength(i)
if (len > max_length) {
max_length <- len
number_with_longest_chain <- i
}
}
return(list("number" = number_with_longest_chain, "length" = max_length))
}
# Encontre o número inicial abaixo de um milhão com a cadeia de Collatz mais longa
result <- longestChain(1000000)
print(result)
> $number
[1] 837799
$length
[1] 525
Truss paths
Starting in the top left corner of a 2x2 grid, you may only be able to move right and down. There are exactly 6 routes to the bottom right.
How many such routes are there through a 20 x 20 grid?
To calculate the number of routes through a 𝑛×𝑛 grid where you can only move right or down, the solution is combinatorial based.
The problem involves choosing n moves to the right and n moves down in any order, which is equivalent to calculating a binomial coefficient.
The formula for the number of routes through an n x n grid is given by:
$$\text{routes} = \binom{2n}{n} = \frac{(2n)!}{(2n-n)!n!}$$
R Code
# Função que calcula o fatorial
factorial <- function(x) {
if (x == 0)
return(1)
return(prod(1:x))
}
# Função para calcular coeficiente binomial (2n escolha n)
binomialCoefficient <- function(n)
return(factorial(2 * n) / (factorial(n) * factorial(n)))
# Number of routes through an n x n grid
gridRoutes <- function(n)
return(binomialCoefficient(n))
# Example: Calculate routes through a 20x20 grid
n <- 20
routes <- gridRoutes(n)
cat("The number of routes through a", n, "x", n, "grid is:", routes, "\n")
> $The number of routes through a 20 x 20 grid is: 137846528820
Version 2
R Code
gridRoutes <- function(n) choose(2*n, n)
# Example: Calculate routes through a 20x20 grid
n <- 20
routes <- gridRoutes(n)
cat("The number of routes through a", n, "x", n, "grid is:", routes, "\n")
> $The number of routes through a 20 x 20 grid is: 137846528820
Sum of Power Digits
$2^{15} = 32768$ and the sum of its digits is $3+2+7+6+8=26$
What is the sum of the digits of the number $2^{1000}$?
R Code
sumPowerDigits <- function(base, power)
return(sum(as.integer(
unlist(strsplit( ## splita os digitos
as.character(
format(base^power, scientific = FALSE)), "")) ## pot sem notação cientifica
)
)
)
sumPowerDigits(2, 15)
> 26
sumPowerDigits(2, 1000)
> 1366
Number letter counts
If the numbers 1 to 5 are written by words: one, two, three, four, five, then there are $3+3+5+4+4=19$ letters used in total.
If all the numbers from 1 to 1000 (one thousand) inclusive were written in words, how many letters would be used?
NOTE: Do not count spaces or hyphens. For example (three hundred and forty-two) contains letters and (one hundred and fifteen) contains Letters. The use of “e” when writing numbers conforms to British usage.
R Code
countLetterNumber <- function(n){
letter2Num <- xfun::n2w(seq(n), cap = TRUE, hyphen = FALSE, and = TRUE)
numNotSpace <- gsub(" ", "", letter2Num)
return(sum(nchar(numNotSpace)))
}
countLellerNumber(5)
> 19
countLellerNumber(1000)
> 21124
Maximum Sum of Path I
Starting at the top of the triangle below and moving to adjacent numbers in the row below, the maximum total from top to bottom is 23.
3
7 4
2 4 6
8 5 9 3
Find the maximum total from top to bottom of the triangle below:
75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23
NOTE: Since there are only 16384 routes, you can resolve this issue by trying all routes. However, Problem 67 is the same challenge with a triangle containing one hundred lines; cannot be solved by brute force and requires a clever method!
R Code
triangulo <- list(
c(3),
c(7, 4),
c(2, 4, 6),
c(8, 5, 9, 3)
)
triangulo1 <- list(
c(75),
c(95, 64),
c(17, 47, 82),
c(18, 35, 87, 10),
c(20, 4, 82, 47, 65),
c(19, 1, 23, 75, 3, 34),
c(88, 2, 77, 73, 7, 63, 67),
c(99, 65, 4, 28, 6, 16, 70, 92),
c(41, 41, 26, 56, 83, 40, 80, 70, 33),
c(41, 48, 72, 33, 47, 32, 37, 16, 94, 29),
c(53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14),
c(70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57),
c(91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48),
c(63, 66, 4, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31),
c(4, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 04, 23)
)
# Função para encontrar a soma máxima do caminho
maxPathSum <- function(triangulo) {
# Copiar o triângulo para não modificar o original
temp <- triangulo
# Iterar de baixo para cima
for (i in (length(temp) - 1):1)
for (j in 1:length(temp[[i]]))
temp[[i]][j] <- temp[[i]][j] + max(temp[[i + 1]][j], temp[[i + 1]][j + 1])
# O topo do triângulo agora contém a soma máxima
return(temp[[1]][1])
}
# Calcular a soma máxima do caminho
maxPathSum(triangulo)
> 23
maxPathSum(triangulo1)
> 1074
Counting the Sundays
You are provided with the following information, but you may prefer to do some research yourself.
- January 1, 1900 was a Monday.
- Thirty days have September, April, June and November.
- Everything else has thirty-one, except February, which has twenty-eight, rain or shine.
- And in leap years, twenty-nine. A leap year occurs in any year equally divisible by 4, but not in a century unless it is divisible by 400.
How many Sundays fell on the first day of the month during the 20th century (January 1, 1901 to December 31, 2000)?
R Code
# Função para verificar se um ano é bissexto
isLeapYear <- function(year)
return((year %% 4 == 0 && year %% 100 != 0) || (year %% 400 == 0))
# Função para calcular o dia da semana do primeiro dia de um mês
dayWeek <- function(year, month) {
# 1º de janeiro de 1900 foi uma segunda-feira
daysMonth <- c(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
totalDays <- 0
# Calcular os dias totais até o ano anterior
totalDays <- sum(sapply(1900:(year - 1), function(y)
ifelse(isLeapYear(y), 366, 365)))
# Calcular os dias totais até o mês anterior
totalDays <- totalDays + sum(daysMonth[1:(month - 1)])
if (month > 2 && isLeapYear(year))
totalDays <- totalDays + 1
return((totalDays + 1) %% 7)
# +1 porque 1º de janeiro de 1900 foi uma segunda-feira
}
# Contar quantos domingos caíram no primeiro dia do mês durante o século XX
countSundays <- function() {
count <- 0
for (year in 1901:2000)
for (month in 1:12)
if (dayWeek(year, month) == 0) # 0 representa domingo
count <- count + 1
return(count)
}
# Calcular e imprimir o resultado
countSundays()
> 171
Sum of the digits of a factorial
$n!$ means $n\times (n-1)\times 3\times 2 \times 1$.
the sum of the digits of the number of $10!$ is 27. Find the sum of the digits in the number of $100!$.
- Exponential Growth: The value of the factorial grows very quickly. For example, ( 10 != 3.628.800 ) and ( 20 != 2.432.902.008.176.640.000 ).
- Computational Limitations: For very large numbers, the standard data types in many programming languages are not sufficient to store the result.
Calculation Techniques
- Iterative Multiplication: The most direct approach is to sequentially multiply the numbers from 1 to ( n ).
- Prime Factor Decomposition: This technique can be used to optimize multiplication, especially in more advanced algorithms.
- Fast Multiplication Algorithms: Algorithms such as Karatsuba or FFT (Fast Fourier Transform) can be used to multiply large numbers more efficiently.
Why does the conventional way of calculating factorial fail for large numbers?
A factorial of 100 has 158 digits. It is not possible to store these many digits even if we use long ints.
The idea is to use basic mathematics for multiplication.
R Code
# Function to multiply two large numbers represented as strings
multiplyLargeNumbers <- function(num1, num2) {
len1 <- nchar(num1)
len2 <- nchar(num2)
result <- rep(0, len1 + len2)
for (i in len1:1) {
carry <- 0
for (j in len2:1) {
product <- as.integer(substr(num1, i, i)) * as.integer(substr(num2, j, j)) + result[i + j] + carry
carry <- product %/% 10
result[i + j] <- product %% 10
}
result[i] <- result[i] + carry
}
result_str <- paste(result, collapse = "")
result_str <- sub("^0+", "", result_str) # Remove leading zeros
return(result_str)
}
# Function to calculate factorial of a number
factorialLarge <- function(n) {
result <- "1"
for (i in 2:n) {
result <- multiplyLargeNumbers(result, as.character(i))
}
return(result)
}
# Function to sum the digits of a large number represented as a string
sumDigits <- function(num) {
digits <- as.integer(unlist(strsplit(num, "")))
return(sum(digits))
}
# Calculate the factorial of 100
fatResp <- factorialLarge(100)
# Calculate the sum of the digits of the factorial
sumDigits(fatResp)
> 648
Name scores
Using names.txt (right click and ‘Save link/target as…’) , a 46K text file containing over five thousand names, start by sorting it in order alphabetical. Then, calculating the alphabetical value of each name, multiply that value by its alphabetical position in the list to obtain a name score.
For example, when the list is sorted alphabetically, COLIN, which is worth 3+15+12+9+14=53, is the 938th name on the list. Thus, COLIN would obtain a score of 938x43=49714.
What is the total of all name scores in the file?
R Code
# Ler o arquivo names.txt
file_path <- "names.txt" # Substitua pelo caminho correto do arquivo
names_data <- readLines(file_path)
# Extrair os nomes e remover aspas
names <- unlist(strsplit(names_data, split = ",")) # Divide os nomes por vírgulas
names <- gsub('"', '', names) # Remove as aspas
# Ordenar os nomes em ordem alfabética
names_sorted <- sort(names)
# Função para calcular o valor alfabético de um nome
get_alpha_value <- function(name) {
sum(match(unlist(strsplit(name, split = "")), LETTERS))
}
# Calcular a pontuação de cada nome
name_scores <- sapply(seq_along(names_sorted), function(i) {
name_value <- get_alpha_value(names_sorted[i])
score <- name_value * i # Multiplica pelo índice
return(score)
})
# Somar todas as pontuações
total_score <- sum(name_scores)
# Resultado final
cat("A pontuação total dos nomes é:", total_score, "\n")
> A pontuação total dos nomes é: 871198282
Non-abundant sums
A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 Would be 1+2+4+7+14=28, which means 28 is a perfect number.
A number n is called deficient if the sum of its own divisors is less than n and is called abundant if this sum exceeds n.
Since 12 is the smallest abundant number, 1+2+3+4+6=16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, It can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced further by analysis, although it is known that the The largest number that cannot be expressed as the sum of two abundant numbers is smaller than this limit.
Find the sum of all positive integers that cannot be written as sum of two abundant numbers.
R Code
# Função eficiente para encontrar a soma dos divisores próprios
sum_of_proper_divisors <- function(n) {
if (n < 2) return(0)
divisors <- c(1) # Começa com 1, que é sempre divisor
sqrt_n <- floor(sqrt(n))
for (i in 2:sqrt_n) {
if (n %% i == 0) {
divisors <- c(divisors, i, n / i)
}
}
# Remover o número duplicado caso seja um quadrado perfeito
divisors <- unique(divisors[divisors != n])
return(sum(divisors))
}
# Limite superior
upper_limit <- 28123
# Identificar números abundantes
abundant_numbers <- which(sapply(1:upper_limit, function(x) sum_of_proper_divisors(x) > x))
# Criar vetor booleano para representar números que podem ser escritos como soma de dois números abundantes
can_be_written <- logical(upper_limit)
# Marcar todas as somas de dois números abundantes
len <- length(abundant_numbers)
for (i in 1:len) {
for (j in i:len) {
sum_ab <- abundant_numbers[i] + abundant_numbers[j]
if (sum_ab > upper_limit) break
can_be_written[sum_ab] <- TRUE
}
}
# Somar os números que NÃO podem ser escritos como soma de dois números abundantes
non_abundant_sum <- sum(which(!can_be_written))
# Resultado final
cat("A soma de todos os inteiros positivos que não podem ser escritos como a soma de dois números abundantes é:", non_abundant_sum, "\n")
> A soma de todos os inteiros positivos que não podem ser escritos como a soma
de dois números abundantes é: 4179871