-
Notifications
You must be signed in to change notification settings - Fork 1
/
relprime.cpp
79 lines (74 loc) · 1.99 KB
/
relprime.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/******************************************************/
/* */
/* relprime.cpp - relatively prime numbers */
/* */
/******************************************************/
/* Copyright 2020 Pierre Abbat.
* This file is part of Wolkenbase.
*
* Wolkenbase is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Wolkenbase is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Wolkenbase. If not, see <http://www.gnu.org/licenses/>.
*/
#include <map>
#include <cmath>
#include "relprime.h"
#include "threads.h"
using namespace std;
const double quadirr[]=
{
#include "quadirr.txt"
};
map<uint64_t,unsigned> relprimes;
shared_mutex primeMutex;
unsigned gcd(unsigned a,unsigned b)
{
while (a&&b)
{
if (a>b)
{
b^=a;
a^=b;
b^=a;
}
b%=a;
}
return a+b;
}
unsigned relprime(unsigned n,int thread)
/* Returns an integer relatively prime to n and close to n*q, where
* q is the threadth quadratic irrational in the Quadlods order.
*/
{
unsigned ret=0,twice;
double phin;
uint64_t inx=((uint64_t)thread<<32)+n;
thread%=6542;
if (thread<0)
thread+=6542;
primeMutex.lock_shared();
if (relprimes.count(inx))
ret=relprimes[inx];
primeMutex.unlock_shared();
if (!ret)
{
phin=n*quadirr[thread];
ret=lrint(phin);
twice=2*ret-(ret>phin);
while (gcd(ret,n)!=1 || (ret>n && n>0))
ret=twice-ret+(ret<=phin);
primeMutex.lock();
relprimes[inx]=ret;
primeMutex.unlock();
}
return ret;
}