寻找素数分配线程算法
Posted qianbo_insist
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了寻找素数分配线程算法相关的知识,希望对你有一定的参考价值。
最近需要求反向最大素数和正向最近素数,
1 计算机器的核心数目
2 拿到大于核心数目且最近的素数
3 拿到反向最大素数,两个算法
场景是,分配合适的线程,并且按照素数分配到合适的线程中去,比如根据URL如请求的是 /xn/live/234来计算hash值,并且将改链接session分配到一个线程中
计算有x个线程
链接为session,session1,session2 …,分配到x1,x2,x3…线程中
show me the code
#pragma once
#include <string.h>
#include <cmath>
#include <thread>
//注意prime是素数
static int rotating_hash(const char *key, int prime)
{
int hash, i;
int len = strlen(key);
for (hash = len, i = 0; i < len; i++)
{
hash = (hash << 4 >> 28) ^ key[i];
return (hash % prime);
}
}
static int hash_add(const char* key, int prime)
{
int hash, i;
int len = strlen(key);
for (hash = len, i = 0; i < len; i++)
hash += key[i];
return (hash % prime);
}
//求核数后面最大的素数
//只能被自己和1整除的数为素数
static int hash_next_prime(int num) {
if (num == 1)
return 2;
if (num == 2)
return 3;
if (num % 2 == 0)
++num;
int i;
bool flag = false;
while (1)
{
flag = false;
for (i = 3; i<num; i += 2)
if (num % i == 0) {
flag = true;
break;
}
if (!flag)
return num;
num += 2;
}
}
//寻找反向最大的素数
static int find_min_s(int a) {
int m = 0;
for (int i = a; i >0; i--) {
m = 0;
for (int j = 2; j <= std::sqrt(i); j++) {
if (i%j == 0) {
m = 1;
break;
}
}
if (m == 0) {
//std::cout << i << " was the max prime";
return i;
}
}
if (m == 0) {
//std::cout << a << " was the max prime";
return a;
}
}
测试
int main()
{
const char * url = "xn/live/234";
const char * url2 = "xn1/live/2345";
const char * url3 = "xn2/live/234";
const char * url4 = "xn/abc/23411";
const char * url5 = "xn/abcd/234";
const char * url6 = "xn/abcd/2345";
const char * url7 = "xn/abcd/2346";
const char * url8 = "xn/abcd/2347";
const char * url9 = "xn/abcd/2348";
const char * url10 = "xn/abcd/2349";
const char * url11 = "xn2/abcd/2349";
cout << hash_add(url, 7) << endl;
cout << hash_add(url2, 7) << endl;
cout << hash_add(url3, 7) << endl;
cout << hash_add(url4, 7) << endl;
cout << hash_add(url5, 7) << endl;
cout << hash_add(url6, 7) << endl;
cout << hash_add(url7, 7) << endl;
cout << hash_add(url8, 7) << endl;
cout << hash_add(url9, 7) << endl;
cout << hash_add(url10, 7) << endl;
cout << hash_add(url11, 7) << endl;
int ct = core_thread();
int g = hash_next_prime(ct);
cout << "the prime is :" << g<<endl;
cout << hash_add(url, g) << endl;
}
得到核数的函数
static int core_thread()
{
static int g_thread_core = 0 ;
if (g_thread_core > 0)
return g_thread_core;
int cpu_core = std::thread::hardware_concurrency();
g_thread_core = hash_next_prime(cpu_core);
return g_thread_core;
}
以上是关于寻找素数分配线程算法的主要内容,如果未能解决你的问题,请参考以下文章
寻找旋转排序数组中的最小值 II(数组二分查找)打印1000以内的所有素数,并从键盘输入一个正整数,判断是否为素数数组元素统计(算法初阶基础知识)