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 p∗q=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;
}