Problem 6 Sum square difference
#include <iostream>
#include <cstdio>
using namespace std;
int work(int n) {
int t1 = 0, t2 = 0;
for(int i = 1; i <= n; i++) {
t1 += i * i;
t2 += i;
}
t2 *= t2;
return t2 - t1;
}
int main(){
printf("%d\n", work(100));
return 0;
}
Problem 7 10001st prime
思路
素数筛法打表
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
const int N = 1e6 + 10;
bool isPrime[N];
int prime[N];
int table(int n) {
int m = (int)sqrt(1.0 * n);
int tot = 0;
fill(isPrime, isPrime + n, true);
isPrime[0] = isPrime[1] = false;
for(int i = 2; i <= n; i++) {
if(isPrime[i]) {
prime[tot++] = i;
for(int j = i*2; j <= n; j += i) {
isPrime[j] = false;
}
}
}
return tot;
}
int main() {
int tot = table(1000000);
int n = 10001;
assert(tot >= n);
printf("%d\n", prime[n-1]);
return 0;
}
Problem 8 Largest product in a series
#include <iostream>
#include <cstdio>
using namespace std;
typedef long long LL;
const int N = 1000 + 10;
LL work() {
char str[N];
for(int i = 0; i < 20; i++) {
scanf(" %s", str + i*50);
}
LL ans = 0;
for(int i = 12; i < 1000; i++) {
LL val = 1;
for(int j = i-12; j <= i; j++) {
val *= str[j]-'0';
}
ans = max(ans, val);
}
return ans;
}
int main() {
printf("%lld\n", work());
return 0;
}
Problem 9 Special Pythagorean triplet
#include <iostream>
#include <cstdio>
using namespace std;
int work() {
int n = 1000, ans = -1;
for(int i = 1; i <= n; ++i) {
for(int j = i+1; j <= n-i; ++j) {
int k = n - i - j;
if(k <= 0) {
break;
}
if(i*i + j*j == k*k) {
ans = i * j * k;
break;
}
}
if(ans != -1) {
break;
}
}
return ans;
}
int main() {
printf("%d\n", work());
return 0;
}
Problem 10 Summation of primes
#include <iostream>
#include <cstdio>
using namespace std;
typedef long long LL;
const int N = 2e6 + 10;
bool isPrime[N];
LL table(int n) {
fill(isPrime, isPrime + n, true);
isPrime[0] = isPrime[1] = false;
LL ans = 0;
for(int i = 2; i <= n; i++) {
if(isPrime[i]) {
ans += i;
for(int j = i*2; j <= n; j += i) {
isPrime[j] = false;
}
}
}
return ans;
}
int main() {
printf("%lld\n", table(2000000));
return 0;
}