T shanks_factor(const T n) { static_assert(std::is_signed<T>::value, "Must be signed"); auto find_factor = [n](const T k) -> T { const T sqrt_kn = isqrt(k * n); T p = sqrt_kn, old_p; T q = (k * n - p * p), old_q = 1; if (q == 0) return k == 1 ? sqrt_kn : 1; auto iterate = [&] { old_p = p; T b = (sqrt_kn + old_p) / q, tmp; p = b * q - old_p; tmp = q, q = old_q + b * (old_p - p), old_q = tmp; }; for (size_t i = 1; i % 2 || !is_square(q); ++i) iterate(); const T sqrt_q = isqrt(q); const T b = (sqrt_kn - p) / sqrt_q; p = b * sqrt_q + p; old_q = sqrt_q, q = (k * n - p * p) / old_q; do iterate(); while (p != old_p); return gcd(n, p); }; const T max_k = std::numeric_limits<T>::max() / n; for (T k = 1; k <= max_k; ++k) { const T f = find_factor(k); if (f != 1 && f != n) return f; } throw std::overflow_error("Can't use a larger multiplier."); }
/// P3(x, a) counts the numbers <= x that have exactly 3 /// prime factors each exceeding the a-th prime. /// Space complexity: O(pi(sqrt(x))). /// int64_t P3(int64_t x, int64_t a, int threads) { print(""); print("=== P3(x, a) ==="); print("Computation of the 3rd partial sieve function"); double time = get_wtime(); vector<int32_t> primes = generate_primes(isqrt(x)); int64_t y = iroot<3>(x); int64_t pi_y = pi_bsearch(primes, y); int64_t sum = 0; threads = ideal_num_threads(threads, pi_y, 100); #pragma omp parallel for num_threads(threads) schedule(dynamic) reduction(+: sum) for (int64_t i = a + 1; i <= pi_y; i++) { int64_t xi = x / primes[i]; int64_t bi = pi_bsearch(primes, isqrt(xi)); for (int64_t j = i; j <= bi; j++) sum += pi_bsearch(primes, xi / primes[j]) - (j - 1); } print("P3", sum, time); return sum; }
void eu064(char *ans) { int oddcount = 0; for (int n = 1; n <= 10000; n++) { int a0 = isqrt(n); if (a0*a0 == n) continue; int a = a0; int m = 0; int d = 1; int i; for (i = 0; a != 2 * a0; i++) { int m1 = d * a - m; int d1 = (n - m1*m1) / d; int a1 = (a0 + m1) / d1; a = a1; m = m1; d = d1; } if (i % 2 == 1) { oddcount++; } } sprintf(ans, "%d", oddcount); }
int64_t S2_hard_mpi(int64_t x, int64_t y, int64_t z, int64_t c, int64_t s2_hard_approx, int threads) { print(""); print("=== S2_hard_mpi(x, y) ==="); print("Computation of the hard special leaves"); print(x, y, c, threads); int64_t s2_hard = 0; double time = get_time(); if (is_mpi_master_proc()) s2_hard = S2_hard_mpi_master(x, y, z, s2_hard_approx); else { FactorTable<uint16_t> factor(y, threads); int64_t max_prime = min(y, z / isqrt(y)); auto primes = generate_primes<int32_t>(max_prime); S2_hard_slave((intfast64_t) x, y, z, c, primes, factor, threads); } print("S2_hard", s2_hard, time); return s2_hard; }
void DFT() //Discrete Fourier Transform //Äèñêðåòíîå ïðåîáðàçîâàíèå ôóðüå { //X(k) = SUMM from n=0 to N-1 (x(n) * exp(-2*pi*i*k*n/N)) for (K = 1; K<= 15; K++) { //ðàñêëàäûâàåì íà: Rex_t = 0; //Re äåéñòâèòåëüíóþ (cos(x) = sin(x + pi/2)) è Imx_t = 0; //Im ìíèìóþ ÷àñòè (sin(x)) for (I = 0; I<=31; I++) { Beta = I * K; Beta = Beta & 31; //Beta < 32 Tmp_s = Sinus[Beta] * Data[I]; //im = sin(ki)*x(i) //2pi = 32 => 2pi/32 = 1 Tmp_c = Sinus[Beta + 7] * Data[I]; //+pi/2 = cos Tmp_s = Tmp_s >> 8; //äëÿ íîðìèðîâêè [-255; 255] ý sin(x) Tmp_c = Tmp_c >> 8; Rex_t = Rex_t + Tmp_c; //SUMM Imx_t = Imx_t - Tmp_s; } Rex_t = Rex_t >> 3; Imx_t = Imx_t >> 3; Tmp_c = Rex_t * Rex_t; //Re^2 Tmp_s = Imx_t * Imx_t; //Im^2 Tmp_c = Tmp_c + Tmp_s; //z^2 = Re^2 + Im^2 Rex[K] = isqrt(Tmp_c); //z } }
//@ ensures \result == 4; int main () { int r; r = isqrt(17); //@ assert r < 4 ==> \false; //@ assert r > 4 ==> \false; return r; }
YINLINE YOPTIMIZE_SPEED int EnergySobel(unsigned char *inp, int bpp, int pitch, int x, int y, int width, int height) { int dx0, dx1, dx2; int dy0, dy1, dy2; int dx = 0; int dy = 0; int s2 = 0; if (1) { dx0 = gradientXCheck(inp, bpp, pitch, x, y, width, height); dx1 = gradientXCheck(inp + 1, bpp, pitch, x, y, width, height); dx2 = gradientXCheck(inp + 2, bpp, pitch, x, y, width, height); dx = (dx0 + 2 * dx1 + dx2) / 4; s2 += dx * dx; } if (1) { dy0 = gradientYCheck(inp, bpp, pitch, x, y, width, height); dy1 = gradientYCheck(inp + 1, bpp, pitch, x, y, width, height); dy2 = gradientYCheck(inp + 2, bpp, pitch, x, y, width, height); dy = (dy0 + 2 * dy1 + dy2) / 4; s2 += dy * dy; } return CLIP_TO_8(isqrt(s2)); }
/// @param start Sieve primes >= start. /// @param stop Sieve primes <= stop. /// @param sieveSize A sieve size in kilobytes. /// @pre start >= 7 /// @pre stop <= 2^64 - 2^32 * 10 /// @pre sieveSize >= 1 && <= 2048 /// SieveOfEratosthenes::SieveOfEratosthenes(uint64_t start, uint64_t stop, uint_t sieveSize) : start_(start), stop_(stop), sieve_(NULL), preSieve_(NULL), eratSmall_(NULL), eratMedium_(NULL), eratBig_(NULL) { if (start_ < 7) throw primesieve_error("SieveOfEratosthenes: start must be >= 7"); if (start_ > stop_) throw primesieve_error("SieveOfEratosthenes: start must be <= stop"); // choose the fastest pre-sieve limit limitPreSieve_ = config::PRESIEVE; if ((stop_ - start_) < config::PRESIEVE_THRESHOLD) limitPreSieve_ = 13; sqrtStop_ = static_cast<uint_t>(isqrt(stop_)); // sieveSize_ must be a power of 2 sieveSize_ = getInBetween(1u, floorPowerOf2(sieveSize), 2048u); sieveSize_ *= 1024; // convert to bytes segmentLow_ = start_ - getByteRemainder(start_); segmentHigh_ = segmentLow_ + sieveSize_ * NUMBERS_PER_BYTE + 1; // allocate the sieve of Eratosthenes array sieve_ = new byte_t[sieveSize_]; init(); }
int64_t S2_hard(int64_t x, int64_t y, int64_t z, int64_t c, int64_t s2_hard_approx, int threads) { #ifdef HAVE_MPI if (mpi_num_procs() > 1) return S2_hard_mpi(x, y, z, c, s2_hard_approx, threads); #endif print(""); print("=== S2_hard(x, y) ==="); print("Computation of the hard special leaves"); print(x, y, c, threads); double time = get_wtime(); FactorTable<uint16_t> factors(y, threads); int64_t max_prime = z / isqrt(y); vector<int32_t> primes = generate_primes(max_prime); int64_t s2_hard = S2_hard_OpenMP_master((intfast64_t) x, y, z, c, (intfast64_t) s2_hard_approx, primes, factors, threads); print("S2_hard", s2_hard, time); return s2_hard; }
YINLINE YOPTIMIZE_SPEED int EnergySobelFast(unsigned char *inp, int bpp, int pitch) { int dx0, dx1, dx2; int dy0, dy1, dy2; int dx = 0; int dy = 0; int s2 = 0; if (1) { dx0 = gradientX(inp, bpp, pitch); dx1 = gradientX(inp + 1, bpp, pitch); dx2 = gradientX(inp + 2, bpp, pitch); dx = (dx0 + 2 * dx1 + dx2) / 4; s2 += dx * dx; } if (1) { dy0 = gradientY(inp, bpp, pitch); dy1 = gradientY(inp + 1, bpp, pitch); dy2 = gradientY(inp + 2, bpp, pitch); dy = (dy0 + 2 * dy1 + dy2) / 4; s2 += dy * dy; } return CLIP_TO_8(isqrt(s2)); }
int setblock( void ) { if (trans.left < 4) /* the real easy part */ { trans.start = trans.next; return 0; } if (trans.left == rows*columns) /* the fairly easy part */ { trans.count = trans.left; trans.left = 0; trans.start = trans.next; trans.row = rows; trans.column = columns; return 1; } /* OK, we got here because there was not enough data to fill the rows * columns array. For the rest of the data in the file we have to break it up into smaller parts. The tricky part. */ trans.row = isqrt((unsigned) trans.left); /* guaranteed minimum of 4 bytes */ trans.column = trans.row; trans.start = trans.next; trans.count = trans.column*trans.row; trans.left -= trans.count; trans.next += trans.count; return 1; }
void Sector::GetCustomSystems(Random& rng) { PROFILE_SCOPED() const std::vector<CustomSystem*> &systems = CustomSystem::GetCustomSystemsForSector(sx, sy, sz); if (systems.size() == 0) return; Uint32 sysIdx = 0; for (std::vector<CustomSystem*>::const_iterator it = systems.begin(); it != systems.end(); it++, sysIdx++) { const CustomSystem *cs = *it; System s(sx, sy, sz, sysIdx); s.p = SIZE*cs->pos; s.name = cs->name; for (s.numStars=0; s.numStars<cs->numStars; s.numStars++) { if (cs->primaryType[s.numStars] == 0) break; s.starType[s.numStars] = cs->primaryType[s.numStars]; } s.customSys = cs; s.seed = cs->seed; if (cs->want_rand_explored) { /* * 0 - ~500ly from sol: explored * ~500ly - ~700ly (65-90 sectors): gradual * ~700ly+: unexplored */ int dist = isqrt(1 + sx*sx + sy*sy + sz*sz); s.explored = ((dist <= 90) && ( dist <= 65 || rng.Int32(dist) <= 40)) || Faction::IsHomeSystem(SystemPath(sx, sy, sz, sysIdx)); } else { s.explored = cs->explored; } m_systems.push_back(s); } }
/// Factor numbers <= y FactorTable(int64_t y, int threads) { if (y > max()) throw primesum_error("y must be <= FactorTable::max()"); y = std::max<int64_t>(8, y); T T_MAX = std::numeric_limits<T>::max(); factor_.resize(get_index(y) + 1, T_MAX); int64_t sqrty = isqrt(y); int64_t thread_threshold = ipow(10, 7); threads = ideal_num_threads(threads, y, thread_threshold); int64_t thread_distance = ceil_div(y, threads); #pragma omp parallel for num_threads(threads) for (int t = 0; t < threads; t++) { int64_t low = 1; low += thread_distance * t; int64_t high = std::min(low + thread_distance, y); primesieve::iterator it(get_number(1) - 1); while (true) { int64_t i = 1; int64_t prime = it.next_prime(); int64_t multiple = next_multiple(prime, low, &i); int64_t min_m = prime * get_number(1); if (min_m > high) break; for (; multiple <= high; multiple = prime * get_number(i++)) { int64_t mi = get_index(multiple); // prime is smallest factor of multiple if (factor_[mi] == T_MAX) factor_[mi] = (T) prime; // the least significant bit indicates // whether multiple has an even (0) or odd (1) // number of prime factors else if (factor_[mi] != 0) factor_[mi] ^= 1; } if (prime <= sqrty) { int64_t j = 0; int64_t square = prime * prime; multiple = next_multiple(square, low, &j); // moebius(n) = 0 for (; multiple <= high; multiple = square * get_number(j++)) factor_[get_index(multiple)] = 0; } } } }
void BlockFormation::setStrength(size_t strength_) { strength = strength_; n_files = isqrt(strength); file_middle = (n_files - 1) * spacing * 0.5f; n_ranks = strength / n_files; rank_middle = (n_ranks - 1) * spacing * 0.5f; incomplete_rank = strength - (n_files * n_ranks); }
void ImgCodeBook::GenerateDistanceTables(void) { DualDist *pDist; long i, Count; Count = VectList.Count(); if(Count == 0) return; SortCodes(); DistList.Resize(Count); pDist = DistList.Addr(0); for(i=0; i<Count; i++) { pDist[i].Origin = isqrt(VectList[i].Mag()); pDist[i].AntiOrigin = isqrt(VectList[i].InvMag()); } }
static int math_sqrt (lua_State *L) { #ifdef LUA_NUMBER_INTEGRAL lua_Number x = luaL_checknumber(L, 1); luaL_argcheck(L, 0<=x, 1, "negative"); lua_pushnumber(L, isqrt(x)); #else lua_pushnumber(L, sqrt(luaL_checknumber(L, 1))); #endif return 1; }
static uint128 sigma1_sum(const uint64 n) { uint32 v = isqrt(n); uint128 ret = 0; for (uint32 i = 1; i <= v; ++i) { uint64 t = n / i; ret += uint128(t) * (uint64(2) * i + t + 1); } ret -= uint128(v) * v * (v + 1); return ret >> 1; }
/* Sort resulting SRV records */ void sortSrvRecords(kms_server_dns_ptr* serverlist, const int answers) { int i; for (i = 0; i < answers; i++) { serverlist[i]->random_weight = (rand32() % 256) * isqrt(serverlist[i]->weight * 1000); } qsort(serverlist, answers, sizeof(kms_server_dns_ptr), kmsServerListCompareFunc1); }
uint64_t PrimeSieve::nthPrime(int64_t n, uint64_t start) { setStart(start); double t1 = getWallTime(); if (n == 0) n = 1; // Like Mathematica else if (n > 0) start = add_overflow_safe(start, 1); else if (n < 0) start = sub_underflow_safe(start, 1); uint64_t stop = start; uint64_t dist = nthPrimeDist(n, 0, start); uint64_t nthPrimeGuess = add_overflow_safe(start, dist); int64_t count = 0; int64_t tinyN = 10000; tinyN = max(tinyN, pix(isqrt(nthPrimeGuess))); while ((n - count) > tinyN || sieveBackwards(n, count, stop)) { if (count < n) { checkLimit(start); dist = nthPrimeDist(n, count, start); stop = add_overflow_safe(start, dist); count += countPrimes(start, stop); start = add_overflow_safe(stop, 1); } if (sieveBackwards(n, count, stop)) { checkLowerLimit(stop); dist = nthPrimeDist(n, count, stop); start = sub_underflow_safe(start, dist); count -= countPrimes(start, stop); stop = sub_underflow_safe(start, 1); } } if (n < 0) count -= 1; checkLimit(start); uint64_t overValue = 3; dist = nthPrimeDist(n, count, start) * overValue; stop = add_overflow_safe(start, dist); NthPrime np; np.findNthPrime(n - count, start, stop); seconds_ = getWallTime() - t1; return np.getNthPrime(); }
int128_t S2_hard(int128_t x, int64_t y, int64_t z, int64_t c, int128_t s2_hard_approx, int threads) { #ifdef HAVE_MPI if (mpi_num_procs() > 1) return S2_hard_mpi(x, y, z, c, s2_hard_approx, threads); #endif print(""); print("=== S2_hard(x, y) ==="); print("Computation of the hard special leaves"); print(x, y, c, threads); double time = get_time(); int128_t s2_hard; // uses less memory if (y <= FactorTable<uint16_t>::max()) { FactorTable<uint16_t> factor(y, threads); int64_t max_prime = min(y, z / isqrt(y)); auto primes = generate_primes<uint32_t>(max_prime); s2_hard = S2_hard_OpenMP((intfast128_t) x, y, z, c, (intfast128_t) s2_hard_approx, primes, factor, threads); } else { FactorTable<uint32_t> factor(y, threads); int64_t max_prime = min(y, z / isqrt(y)); auto primes = generate_primes<int64_t>(max_prime); s2_hard = S2_hard_OpenMP((intfast128_t) x, y, z, c, (intfast128_t) s2_hard_approx, primes, factor, threads); } print("S2_hard", s2_hard, time); return s2_hard; }
/*{{{ m_fcircleto*/ void m_fcircleto(int bitmap, int cx, int cy, int rx, int ry) { int x,y,asp,ry2=ry*ry; asp=(rx*100)/ry; for (y=0; y<=ry; y++) { x=(isqrt(ry2-y*y)*asp)/100; m_lineto(bitmap,cx-x,cy+y,cx+x,cy+y); m_lineto(bitmap,cx-x,cy-y,cx+x,cy-y); } }
static uint32_t calc_SSE_H(int16_t *DCT_A, int16_t *DCT_B, uint8_t *IMG_A, uint8_t *IMG_B, int stride) { DECLARE_ALIGNED_MATRIX(sums, 1, 8, uint16_t, CACHE_LINE); DECLARE_ALIGNED_MATRIX(squares, 1, 8, uint32_t, CACHE_LINE); uint32_t i, Global_A, Global_B, Sum_A = 0, Sum_B = 0; uint32_t local[8], MASK_A, MASK_B, Mult1 = 64, Mult2 = 64; /* Step 1: Calculate CSF weighted energy of DCT coefficients */ Sum_A = coeff8_energy(DCT_A); Sum_B = coeff8_energy(DCT_B); /* Step 2: Determine local variances compared to entire block variance */ Global_A = blocksum8(IMG_A, stride, sums, squares); Global_B = blocksum8(IMG_B, stride, &sums[4], &squares[4]); for (i = 0; i < 8; i++) local[i] = (squares[i]<<4) - (sums[i]*sums[i]); /* 16*Var(Di) */ squares[0] += (squares[1] + squares[2] + squares[3]); squares[4] += (squares[5] + squares[6] + squares[7]); Global_A = (squares[0]<<6) - Global_A*Global_A; /* 64*Var(D) */ Global_B = (squares[4]<<6) - Global_B*Global_B; /* 64*Var(D) */ /* Step 3: Calculate contrast masking threshold */ if (Global_A) Mult1 = ((local[0]+local[1]+local[2]+local[3])<<8) / Global_A; if (Global_B) Mult2 = ((local[4]+local[5]+local[6]+local[7])<<8) / Global_B; MASK_A = isqrt(2*Sum_A*Mult1) + 16; MASK_B = isqrt(2*Sum_B*Mult2) + 16; if (MASK_B > MASK_A) /* MAX(MASK_A, MASK_B) */ MASK_A = ((MASK_B + 32) >> 6); else
void test (unsigned x) { unsigned y = isqrt (x); printf ("sqrt (%10u) = %10u %10u <= %10u < %10llu\n", x, y, y * y, x, (unsigned long long) (y + 1) * (y + 1)); if ((unsigned long long) y * y > x) printf ("Error! y * y > x\n"); if (x >= (unsigned long long) (y + 1) * (y + 1)) printf ("Error! x >= (y + 1) * (y + 1)\n"); }
int perfect(long long a, long long *s) { long long r; if (a < 0) return 0; r = isqrt(a); if ((r * r) != a) return 0; (*s) = r; return 1; }
bool SectorCustomSystemsGenerator::Apply(Random& rng, RefCountedPtr<Galaxy> galaxy, RefCountedPtr<Sector> sector, GalaxyGenerator::SectorConfig* config) { PROFILE_SCOPED() const int sx = sector->sx; const int sy = sector->sy; const int sz = sector->sz; if ((sx >= -m_customOnlyRadius) && (sx <= m_customOnlyRadius-1) && (sy >= -m_customOnlyRadius) && (sy <= m_customOnlyRadius-1) && (sz >= -m_customOnlyRadius) && (sz <= m_customOnlyRadius-1)) config->isCustomOnly = true; const std::vector<const CustomSystem*> &systems = galaxy->GetCustomSystems()->GetCustomSystemsForSector(sx, sy, sz); if (systems.size() == 0) return true; Uint32 sysIdx = 0; for (std::vector<const CustomSystem*>::const_iterator it = systems.begin(); it != systems.end(); ++it, ++sysIdx) { const CustomSystem *cs = *it; Sector::System s(sector.Get(), sx, sy, sz, sysIdx); s.m_pos = Sector::SIZE*cs->pos; s.m_name = cs->name; for (s.m_numStars=0; s.m_numStars<cs->numStars; s.m_numStars++) { if (cs->primaryType[s.m_numStars] == 0) break; s.m_starType[s.m_numStars] = cs->primaryType[s.m_numStars]; } s.m_customSys = cs; s.m_seed = cs->seed; if (cs->want_rand_explored) { /* * 0 - ~500ly from sol: explored * ~500ly - ~700ly (65-90 sectors): gradual * ~700ly+: unexplored */ int dist = isqrt(1 + sx*sx + sy*sy + sz*sz); if (((dist <= 90) && ( dist <= 65 || rng.Int32(dist) <= 40)) || galaxy->GetFactions()->IsHomeSystem(SystemPath(sx, sy, sz, sysIdx))) s.m_explored = StarSystem::eEXPLORED_AT_START; else s.m_explored = StarSystem::eUNEXPLORED; } else { if (cs->explored) s.m_explored = StarSystem::eEXPLORED_AT_START; else s.m_explored = StarSystem::eUNEXPLORED; } sector->m_systems.push_back(s); } return true; }
/// Partial sieve function (a.k.a. Legendre-sum). /// phi(x, a) counts the numbers <= x that are not divisible /// by any of the first a primes. /// int64_t phi(int64_t x, int64_t a, int threads) { if (x < 1) return 0; if (a > x) return 1; if (a < 1) return x; print(""); print("=== phi(x, a) ==="); print("Count the numbers <= x coprime to the first a primes"); double time = get_wtime(); int64_t sum = 0; if (is_phi_tiny(a)) sum = phi_tiny(x, a); else { vector<int32_t> primes = generate_n_primes(a); if (primes.at(a) >= x) sum = 1; else { // use a large pi(x) lookup table for speed int64_t sqrtx = isqrt(x); PiTable pi(max(sqrtx, primes[a])); PhiCache cache(primes, pi); int64_t pi_sqrtx = min(pi[sqrtx], a); sum = x - a + pi_sqrtx; int64_t p14 = ipow((int64_t) 10, 14); int64_t thread_threshold = p14 / primes[a]; threads = ideal_num_threads(threads, x, thread_threshold); // this loop scales only up to about 8 CPU cores threads = min(8, threads); #pragma omp parallel for schedule(dynamic, 16) \ num_threads(threads) firstprivate(cache) reduction(+: sum) for (int64_t a2 = 0; a2 < pi_sqrtx; a2++) sum += cache.phi<-1>(x / primes[a2 + 1], a2); } } print("phi", sum, time); return sum; }
/* false means donÕt fire this (itÕs in a floor or ceiling or outside of the map), otherwise the monster that was intersected first (or NONE) is returned in target_index */ bool preflight_projectile( world_point3d *origin, short origin_polygon_index, world_point3d *destination, angle delta_theta, short type, short owner, short owner_type, short *obstruction_index) { bool legal_projectile= false; struct projectile_definition *definition= get_projectile_definition(type); (void) (delta_theta); /* will be used when we truly preflight projectiles */ (void) (owner_type); if (origin_polygon_index!=NONE) { world_distance dx= destination->x-origin->x, dy= destination->y-origin->y; angle elevation= arctangent(isqrt(dx*dx + dy*dy), destination->z-origin->z); if (elevation<MAXIMUM_PROJECTILE_ELEVATION || elevation>FULL_CIRCLE-MAXIMUM_PROJECTILE_ELEVATION) { struct polygon_data *origin_polygon= get_polygon_data(origin_polygon_index); // LP note: "penetrates media boundary" means "hit media surface and continue"; // it will act like "penetrates_media" here // Added idiot-proofing to media data media_data *media = get_media_data(origin_polygon->media_index); if (origin->z>origin_polygon->floor_height && origin->z<origin_polygon->ceiling_height && (origin_polygon->media_index==NONE || definition->flags&(_penetrates_media) || (media ? origin->z>media->height : true))) { /* make sure it hits something */ uint16 flags= translate_projectile(type, origin, origin_polygon_index, destination, (short *) NULL, owner, obstruction_index, 0, true, NONE); *obstruction_index= (flags&_projectile_hit_monster) ? get_object_data(*obstruction_index)->permutation : NONE; legal_projectile= true; } } } return legal_projectile; }
/* determine next available prime number */ static int next_prime(const int num) { int nprime, factor, root; /* nprime has to be larger than num and odd */ nprime = num + (num & 1) + 1; /* there is always a prime between n and 2n */ while (nprime < 2*num) { /* brute force division test on odd factors up to sqrt(nprime) */ root = isqrt(nprime)+1; for (factor = 3; factor < root; factor +=2) { if (nprime % factor == 0) break; } /* if the loop didn't exit early, we have found a prime */ if (factor >= root) return nprime; nprime += 2; } return nprime; }
static int IsOddPrime( unsigned int x ) { register unsigned int root; register unsigned int i; root = isqrt(x); for( i=2; i<MAXPRIMES-1; i++ ) { if( (x%primes[i]) == 0 ) return False; if( (unsigned int) primes[i] >= root ) return True; } for( i=primes[MAXPRIMES-1]; i<=root; i+=2 ) if( (x%i) == 0 ) return False; return True; }
int _tmain(int argc, _TCHAR* argv[]) { //input unsigned long long maxPrime = 500000000; unsigned long long maxSearch = isqrt(maxPrime); //creating a bit string the length of maxSearch bool * bitString; bitString = (bool *)malloc((sizeof(bool)*maxPrime) + 1); //initialise bit string to true's for(unsigned long long i = 0; i < maxPrime; i++) bitString[i] = false; //sieve //let [1] = 1 unsigned long long counter; unsigned long long j; for(counter = 2; counter < maxSearch; counter++) //small optimisation starting from square of number for(j = counter * counter; j < maxPrime; j += counter) (bitString[j] ? 0 : bitString[j] = true ); //once bitString is completed print it to file: FILE *file; if (file = fopen("dataOutput.txt", "w")) { for(unsigned long long i = 2; i < maxPrime; i++) if(!bitString[i]) fprintf(file, "%d\n", i); } else{ printf("Output file failed to open"); } return 0; }