介是相亲数的介绍
http://zh.wikipedia.org/wiki/%E7%9B%B8%E4%BA%B2%E6%95%B0
介是代码
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>
#define MAX_THREAD 128
static size_t thread_num = 1;
static size_t start = 2;
static size_t end = -1;
static size_t found[MAX_THREAD] = {0};
static inline size_t sum_of_proper_divisors(size_t n)
{
size_t sum, i, ixi;
for(i = 2, sum = 1; (ixi = i*i) <= n; i++) {
if(ixi != n) {
if(n % i == 0) {
sum += i + n/i;
}
} else {
sum += i;
}
}
return sum;
}
static void * thread_main(void * arg)
{
size_t id = (size_t)arg;
size_t i = start + id;
struct timeval tv;
gettimeofday(&tv, NULL);
double t1 = tv.tv_sec + tv.tv_usec / 1e6;
for(;;) {
size_t s = sum_of_proper_divisors(i);
if(s > i) {
if(sum_of_proper_divisors(s) == i) {
printf("%zu %zu\n", i, s);
found[id]++;
}
}
size_t next = i + thread_num;
if(next <= end && next > i) {
i = next;
} else {
break;
}
}
gettimeofday(&tv, NULL);
double t2 = tv.tv_sec + tv.tv_usec / 1e6;
fprintf(stderr, "=== thread:%zd found:%zd time:%f (sec) ===\n", id, found[id], t2-t1);
return NULL;
}
static void usage(const char * appname)
{
fprintf(stderr,
"Usage: %s [options]\n"
"Options:\n"
" -t Threads number ( 1 <= t <= %u )\n"
" -s Start number ( s >= 2 )\n"
" -e End number ( e > s )\n"
" -h Help\n",
appname, MAX_THREAD);
}
int main(int argc, char * argv[])
{
int ch;
opterr = 0;
while((ch = getopt(argc, argv, "t:s:e:h")) != -1) {
switch(ch) {
case 't':
thread_num = atoll(optarg);
break;
case 's':
start = atoll(optarg);
break;
case 'e':
end = atoll(optarg);
break;
case 'h':
usage(argv[0]);
return 0;
default:
usage(argv[0]);
return 1;
}
}
if(!(1 <= thread_num && thread_num <= MAX_THREAD && start >= 2 && end > start)) {
usage(argv[0]);
return 2;
}
fprintf(stderr, "=== thread_num:%zu start:%zu end:%zu ===\n", thread_num, start, end);
pthread_t pid[MAX_THREAD];
size_t i;
for(i = 1; i < thread_num; i++) {
pthread_create(pid+i, NULL, thread_main, (void*)i);
}
thread_main(0);
for(i = 1; i < thread_num; i++) {
pthread_join(pid[i], NULL);
}
return 0;
}
介是编译方法(是的,是-pthread 不是 -lpthread,两者有区别)
gcc -Wall -pthread xqs.c -o xqs
介是使用方法举例
./xqs -t 2 -e 800000 | sort -n
=== thread_num:2 start:2 end:800000 ===
=== thread:1 found:6 time:1.287065 (sec) ===
=== thread:0 found:31 time:2.117775 (sec) ===
220 284
1184 1210
2620 2924
5020 5564
6232 6368
10744 10856
12285 14595
17296 18416
63020 76084
66928 66992
67095 71145
69615 87633
79750 88730
100485 124155
122265 139815
122368 123152
141664 153176
142310 168730
171856 176336
176272 180848
185368 203432
196724 202444
280540 365084
308620 389924
319550 430402
356408 399592
437456 455344
469028 486178
503056 514736
522405 525915
600392 669688
609928 686072
624184 691256
635624 712216
643336 652664
667964 783556
726104 796696