project euler 1~5

Problem 1 Multiples of 3 and 5

在这里插入图片描述

#include <iostream>
#include <cstdio>

using namespace std;

int work(int n) {
    int ans = 0;
    for(int i = 0; i < n; i++) {
        ans += (i%3 == 0 || i%5 == 0) ? i : 0;
    }
    return ans;
}

int main() {
    printf("%d\n", work(1000));
    return 0;
}

Problem 2 Even Fibonacci numbers

在这里插入图片描述

#include <iostream>
#include <cstdio>

using namespace std;

int work(int limit) {
    int ans = 0;
    int a = 0, b = 1;
    while(true) {
        int cur = a + b;
        if(cur > limit) {
            break;
        }
        if(cur % 2 == 0) {
            ans += cur;
        }
        a = b;
        b = cur;
    }
    return ans;
}

int main() {
    printf("%d\n", work(4000000));

    return 0;
}

Problem 3 Largest prime factor

在这里插入图片描述

思路

对于一个数字 n n n,最大质因数 p p p分两种情况:

  • p < = n p <= \sqrt{n} p<=n ,那么只需要从 2 2 2遍历到 n \sqrt{n} n 取最大可整除 n n n的质数
  • p > = n p >= \sqrt{n} p>=n ,此时有 p ∗ q = n p*q=n pq=n q q q一定小于 n \sqrt{n} n ,此时让 n n n除掉 2 2 2 n \sqrt{n} n 以内可被 n n n整除的所有值,最后剩下的值就是 p p p
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>

using namespace std;

typedef long long LL;

const int N = 1e6 + 10;

LL work(LL n) {
    int m = (int)sqrt(1.0 * n);
    LL ans = -1;
    for(int i = 2; i <= m; i++) {
        while(n % i == 0) {
            n /= i;
            ans = max(ans, (LL)i);
        }
    }
    if(n > m) {
        ans = n;
    }
    return ans;
}

int main() {
    LL n = 600851475143L;
    printf("%lld\n", work(n));

    return 0;
}

Problem 4 Largest palindrome product

在这里插入图片描述

#include <iostream>
#include <cstdio>

using namespace std;

bool check(int n) {
    if(n % 10 == 0) {
        return false;
    }
    int m = 0;
    while(n > m) {
        m = m * 10 + n % 10;
        n /= 10;
    }
    return n/10 == m || n == m;
}

int work() {
    int ans = -1;
    for(int i = 999; i >= 100; i--) {
        for(int j = 999; j >= 100; j--) {
            if(check(i * j) && ans < i * j) {
                ans = i * j;
                break;
            }
        }
    }
    return ans;
}

int main() {
    printf("%d\n", work());

    return 0;
}

Problem 5 Smallest multiple

在这里插入图片描述

#include <iostream>
#include <cstdio>

using namespace std;

int gcd(int a, int b) {
    return !b ? a : gcd(b, a%b);
}

int gcm(int a, int b) {
    return a / gcd(a, b) * b;
}

int work(int n) {
    int ans = 1;
    for(int i = 1; i <= n; i++) {
        ans = gcm(ans, i);
    }
    return ans;
}

int main() {
    printf("%d\n", work(20));

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值