3 或 5 的倍数

如果我们列出 10 以下的所有自然数,并且是 3 或 5 的倍数,我们得到 3、5、6 和 9。这些倍数的总和是23。

求 1000 下面的 3 或 5 的所有倍数之和。

R代码
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

甚至斐波那契数列

斐波那契数列中的每一项新项都是通过将前两项相加而生成的。开始于 1和2,第一个10。条款如下:

$$1,2,3,5,8,13, 21, 34, 55, 89, \dots$$

当考虑斐波那契数列中值不超过四百万的项时,求偶数项的和。

R代码
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

最大素因数

13195 的质因数为 5、7、13 和 29。

数字 600851475143 的最大质因数是多少?

R代码
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

最大回文积

回文数的两种读法都是相同的。由两个 2 位数字的乘积组成的最大回文数

$$ 9009 = 91 \times 99$$

找到由两个 3 位数字的乘积组成的最大回文数。

R代码
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

最小倍数

2520 是可以被1 到10 中的每个数字整除且没有余数的最小数字。

能被 1 到 20 之间所有数字整除的最小正数是多少?

R代码

## 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

平方和差

前十个自然数的平方和为:

$$1^2+ 2^2 + \dots + 10^2 = 385$$

前十个自然数之和的平方为,

$$(1+2+\dots + 10)^2 = 55^2 = 3025$$

因此,前十个自然数的平方和与和的平方之差为

$$3025-385=2640$$

求前一百个自然数的平方和与总和的平方之间的差。

R代码
vec <- 1:100
difsomaquad <- function(valmax) sum(seq(valmax))^2 - sum(seq(valmax)^2)

difsomaquad(10)
> 2640
difsomaquad(100)
> 25164150

10001堂弟

列出前六个质数时:

$$2,3,5,7,11,13$$

我们可以看到第六个质数是13。

第 10001 个素数是多少?

R代码

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

系列中最大的产品

乘积最大的千位数字中相邻的四位数字是

$$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

找出第 1000 位数字中具有最佳乘积的 13 个相邻数字。这个产品的价值是什么?

R代码

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

特殊毕达哥拉斯套装

毕达哥拉斯三元组是具有 $a< b< c$ 的三个自然数的集合,其中:

$$a^2+ b^2 = c^2$$

例如,

$$3^2+ 4^2 = 9 + 16 = 25 = 5^2$$

恰好有一套毕达哥拉斯套装适合

$$a+b+c=1000$$

查找产品

$$abc$$
R代码
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

素数之和

fr 10 以下素数之和为:

$$2+3+5+7=17$$

求 200 万以下的所有素数之和。

R代码

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

网格中最大的产品

在下面的20 x 20网格中,沿对角线的四个数字被标记为红色。

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代码

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

最大可整除三角形数

三角数序列是通过自然数相加生成的。因此,三角形中的第七个数字是

$$1+2+3+4+5+6+7=28$$

前十项是:

$$1,3,6,10,15,21,28,36,45,55,\dots$$
$$ \begin{align} \mathbf 1 &\colon 1\\ \mathbf 3 &\colon 1,3\\ \mathbf 6 &\colon 1,2,3,6\\ \mathbf{10} &\colon 1,2,5,10\\ \mathbf{15} &\colon 1,3,5,15\\ \mathbf{21} &\colon 1,3,7,21\\ \mathbf{28} &\colon 1,2,4,7,14,28 \end{align} $$

我们可以看到 28 是第一个拥有超过 5 个约数的三角形数。 三角形中第一个有超过五百个约数的数字的值是多少?

R代码

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

版本 2

R代码

# 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

大额金额

计算接下来的一百位50位数字之和的前十位数字。

37107287533902102798797998220837590246510135740250
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代码

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

科拉兹长序列

为正整数集定义以下迭代序列:

$$n \rightarrow \frac{n}{2} \quad \text{n par}$$

$$n \rightarrow 3n+1 \quad \text{n ímpar}$$

使用上面的规则并从 13 开始,我们生成以下序列:

$$13 \rightarrow 40\rightarrow 20 \rightarrow 10 \rightarrow 5 \rightarrow 16 \rightarrow 8 \rightarrow 4 \rightarrow 2 \rightarrow 1$$

可以看出,这个序列(从13开始到1结束)包含10项。尽管尚未得到证明(Collat​​z 问题),但据信所有起始数字都以 1 结尾。

哪个起始数字(低于 100 万)会产生最长的链?

**注意:**一旦链开始,截止日期可能会超过一百万。

R代码
# 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

桁架路径

从 2x2 网格的左上角开始,您可能只能向右和向下移动。右下角正好有 6 条路线。

通过 20 x 20 网格有多少条这样的路线?

计算通过 𝑛×𝑛 网格的路线数量 如果您只能向右或向下移动,则解决方案是基于组合的。

该问题涉及以任意顺序选择n次向右移动和n次向下移动,这相当于计算二项式系数。

通过 n x n 网格的路线数的公式如下:

$$\text{routes} = \binom{2n}{n} = \frac{(2n)!}{(2n-n)!n!}$$

​

R代码

# 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

版本 2

R代码

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

幂位总和

$2^{15} = 32768$ 其各位数字之和为 $3+2+7+6+8=26$

数字$2^{1000}$的各位数字之和是多少?

R代码
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

数字字母计数

如果数字1到5用单词写成:一、二、三、四、五,那么总共使用了$3+3+5+4+4=19$个字母。

如果从1到1000(一千)的所有数字都用文字写出来,需要多少个字母?

注意: 不要计算空格或连字符。例如,(342) 包含字母,(115) 包含字母。书写数字时使用“e”符合英国习惯。

R代码

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

路径 I 的最大和

从下方三角形的顶部开始,移动到下方行中的相邻数字,从上到下的最大总数为 23。

3
7 4

2 4 6
8 5 9 3

求下面三角形从上到下的最大总数:

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

**注意:**由于只有 16384 条路由,因此您可以通过尝试所有路由来解决此问题。然而,问题 67 与包含一百条线的三角形具有相同的挑战;无法用蛮力解决,需要巧妙的方法!

R代码
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

数着星期天

我们向您提供了以下信息,但您可能更愿意自己做一些研究。

  • 1 月 1 日,1900 是星期一。
  • 三十天有九月、四月、六月和十一月。
  • 其他一切都有三十一,除了二月,无论风雨无阻,二月都有二十八。
  • 闰年是二十九岁。闰年出现在任何能被 4 整除的年份中,但不会出现在一个世纪中,除非它能被 400 整除。

20 世纪期间每月的第一天有多少个星期日(1 月 1 日,1901 到 12 月 31,2000)?

R代码
# 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

阶乘的数字之和

$n!$ 表示$n\times (n-1)\times 3\times 2 \times 1$。

$10!$的数字之和为27。 求 $100!$ 中的数字之和。

  • **指数增长:**阶乘的值增长得非常快。例如,( 10 != 3.628.800 ) 和 ( 20 != 2.432.902.008.176.640.000 )。
  • **计算限制:**对于非常大的数字,许多编程语言中的标准数据类型不足以存储结果。

计算技巧

  • **迭代乘法:**最直接的方法是将 1 到 ( n ) 的数字依次相乘。
  • **质因数分解:**此技术可用于优化乘法,特别是在更高级的算法中。
  • **快速乘法算法:**Karatsuba 或 FFT(快速傅里叶变换)等算法可用于更有效地乘以大数。

为什么计算阶乘的传统方法对于大数会失败?

100 的阶乘有 158 位。即使我们使用长整型,也不可能存储这么多数字。

这个想法是使用基础数学进行乘法。

R代码


# 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.txt(右键单击并“将链接/目标另存为…”) , 一个包含五千多个名字的 46K 文本文件,首先按顺序对其进行排序 按字母顺序排列。然后,计算每个名字的字母值,乘以该值 通过其在列表中的字母位置来获取名称分数。

例如,当列表按字母顺序排序时,COLIN 值得 3+15+12+9+14=53,是列表中的第 938 个名称。因此,COLIN 将获得 938x43=49714 的分数。

文件中所有姓名分数的总和是多少?

R代码
# 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

金额不充裕

完美数是其真因数之和为的数 完全等于数字。例如,真因数之和 28 将是 1+2+4+7+14=28,这意味着 28 是一个完全数。

如果一个数 n 自身约数之和小于 n,如果这个总和超过 n,则称为丰富。

由于12是最小丰富数,因此1+2+3+4+6=16, 可以写成两个丰富数的和是24。通过数学分析, 可以证明所有大于28123的整数 可以写成两个丰富数的和。然而,这 上限无法通过分析进一步降低,尽管已知 不能表示为两个丰富数之和的最大数小于此限制。

求所有不能写成的正整数之和 两个丰富数的和。

R代码
# 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