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

本文分享了解决欧拉计划中的两道编程题目的方法。第一题使用C++处理大数相加,通过数组记录每位数字并进行进位操作。第二题涉及Collatz序列,用递归函数计算每个起始数的序列长度,寻找产生最长链的起始数。代码实现简洁,但第二题的递归可能会导致较慢的运行时间。
摘要由CSDN通过智能技术生成

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

欧拉计划:https://projecteuler.net/problem=13

Problem 13
Work out the first ten digits of the sum of the following one-hundred 50-digit numbers.

问题13
求出下列100个50位数字之和的前十位数字。

在这里插入图片描述
其余略,具体请到网站查看。

思路分析:简单来说,看到这个题,第一个想法你要是想用大整数,那我劝这位年轻人耗子尾汁,这道题已知要处理的各项数字,就不要用大整数了,直接使用数组记录每一位的值,每十进一就行,你问我50位怎么处理?字符串导入不就行了。挺简单的,直接看代码吧。

#include<stdio.h>
#include<string.h>

char num[55];
int ans[55] = {0};

int main() {
    for(int i = 0; i < 100; i++) {
        scanf("%s",num); 
        int len = strlen(num);
        if(ans[0] < len) ans[0] ;= len
        for (int i = 0; i <len; i++) {
            ans[len - i] += (num[i] - '0');
        }
        for (int i = 1; i <= ans[0]; i++) {
            if(ans[i] < 10) continue;
            ans[i + 1] += ans[i] / 10;
            ans[i] %= 10;
            ans[0] += (i == ans[0]);
        } 
    }
    for (int i = ans[0]; i >= ans[0] - 10; i--) {
        printf("%d", ans[i]);
    }
    printf("\n");
    return 0;
}

如果嫌麻烦就直接拿头文件导入吧。

验证answer = 5537376230

Problem 14
The following iterative sequence is defined for the set of positive integers:
n → n/2 (n is even)
n → 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
NOTE: Once the chain starts the terms are allowed to go above one million.

问题14
以下迭代序列定义为正整数集合:
n→n/2(n是偶数)
n→3n1(n是奇数)
使用上面的规则,从13开始,我们生成以下序列:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
可以看出,这个序列(从13开始,到1结束)包含10个项。 虽然它还没有被证明(Collatz问题),但人们认为所有的起始数都在1完成。
哪个起始数,在一百万以下,产生最长的链?
注:一旦链启动,条款允许超过100万。

解题思路:这题看到的时候没什么想法,只有两个递归用的公式,也没多想,直接递归就过了,因为备注的内容所以也不用太考虑数字范围的问题,每次考虑链的长度记录最大值就好。不过一百万的循环还是挺费时间的,应该可以优化,欢迎各位大佬提出建议。

#include<stdio.h>
#define max_n 1000000

long long get_len(long long x) {
    if (x == 1) return 1;
    if (x & 1) return get_len(x * 3 + 1) + 1;
    return get_len(x >> 1) + 1;
}

int main() {
    int ans = 0, num = 0;
    for (int  i = 1; i < max_n; i++) {
        int l = get_len(i);
        if (l > ans) ans = l, num = i;
    }
    printf("%d\n", num);
    return 0;
}

验证answer = 837799

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值