计算机数学和算法习题和解答(1~3)

本文解决三个数学编程问题:一是计算1000以内3或5的倍数之和;二是计算斐波那契数列中小于400万的偶数项之和;三是找出600851475143的最大质因数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. If we list all the 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 the multiples of 3 or 5 below 1000.

找到小于1000的 而且 是3或者5的倍数的 自然数,求它们的和。

x <- 1
sum <- 0
while (x < 1000) {
  if (x%%3==0 | x%%5==0) {
    sum <- sum + x
  }
  x <- x + 1
}
print(sum)


2. Each new term in the Fibonacci sequence(http://baike.baidu.com/view/1074762.htm) is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

有一个小于400万的斐波那契数列,求其中的偶数和。

i <- 2
x <- 1:2
while (x[i]<4000000) {
  x[i+1] <- x[i-1]+x[i]
  i <- i+1
}
sum(x[x%%2==0])


3. The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 600851475143 ?

600851475143的最大质数因子。

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:111
# x[sapply(x,findprime)]

maxfactor <- 0
n <- 110
for (i in seq(from=3, to=round(sqrt(n))+1, by=2)) {
  if (findprime(i) & (n %% i == 0)) {
    #i是质数因子
    n <- n / i
    maxfactor <- i       
    if (i >= n) break
  }
}
print(maxfactor)
参考文章求最大质因子的N种境界


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值