欧拉计划--C++编程突破1

欧拉计划–C++编程突破1

欧拉计划网址: https://projecteuler.net

Problem 1
Multiples of 3 and 5If 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.

3或5的倍数在小于10的自然数中,3或5的倍数有3、5、6和9,这些数之和是23。
求小于1000的自然数中所有3或5的倍数之和。

解题思路:首先考虑数值范围,确定数据类型,最大不超过1000之前的数得和,int类型,然后五和三的倍数,只需要计算五的倍数和三的倍数,再减去同时是五和三的倍数即可(因为同时是五和三倍数的数)

#include<stdio.h>

int is_val(int x) {
    if(x % 3 == 0 || x % 5 == 0) return 1;
    return 0;
}
int main() {
    int sum = 0;
    for (int i = 1; i < 1000; i++) {
        if (is_val(i)) sum += i;
    }
    printf("%d\n", sum);
    return 0;
}

另外,此题还有另一种想法:既然要计算倍数,不如直接将其看为等差数列进行计算,即:
3的倍数 = (3 + 999) * 333 / 2
(第一个倍数+最后一个倍数) * 项数 / 2。
5的倍数 = (5 + 995) * 199 / 2
3和5的倍数 = (15 + (1000 / 15) * 15) * (1000 / 15) / 2;

最后用同样的方法得出结果。代码略。

验证answer = 233168。

Problem 2
Even Fibonacci numbersEach new term in the Fibonacci sequence 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.

偶斐波那契数斐波那契数列中的每一项都是前两项的和。由1和2开始生成的斐波那契数列的前10项为:
1,2,3,5,8,13,21,34,55,89,…
考虑该斐波那契数列中不超过四百万的项,求其中为偶数的项之和。

解题思路:首先数据范围为四百万,考虑记录为宏定义,然后根据斐波那契数列的特点,得到通式f[n] = f[n-1] + f[n-2], 通过数组记录斐波那契数列,(这里需要进行一步估算,题目没有给出斐波那契数列的长度,需要自己估算)根据f[n-1] >= 0.5f[n] (仔细想,f[n] = f[n-1] + f[n-2],f[n-2] 肯定小于 f[n-1],所以能够得出f[n - 1] >= 0.5f[n]的结论),再往下考虑一层,f[n - 2] >= 0.5f[n-1] ,因此可以得出f[n] >= 1.5f[n-1],因此可以得到f[n] >= 1.5^n 这样的结论,因此可以根据log1.5(4000000)的结果推断出大致的位数,大致是37点多,我这里使用的是45。最后将偶数项提取出即可。

#include <stdio.h>
#define max_n 4000000
int fib[45];

int main() {
    fib[1] = 1,fib[2] = 2;
    int n = 2;
    while (fib[n - 1] + fib[n] < max_n) {
        n++;
        fib[n] = fib[n - 1] + fib[n - 2];
    }
    printf("%d\n", n);
    long long sum = 0;
    for (int i = 1; i <= n; i++) {
        if(fib[i] % 2) continue;
        sum += fib[i];
    }
    printf("%lld\n", sum);
    return 0;
}

此题还有很多其他做法,不过原理类似,不多做概述,只简单说一下取偶数的处理。

处理偶数可以使用按位&运算来进行,像这样:

if(!(x & 1)) {	
    sum += x;
}

其中x&1是按位与运算,将两个数的二进制对应每位分别进行与运算,得到结果,一般通过x & 1来判断一个属是否是偶数,如果返回为1则为奇数,如果返回为0则为偶数,具体原因请独立思考,此处不再赘述。

验证answer = 4613732

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值