diff --git a/src/util/integerfactoring.c b/src/util/integerfactoring.c index 476a616b43..ff4cd1d9a0 100644 --- a/src/util/integerfactoring.c +++ b/src/util/integerfactoring.c @@ -20,7 +20,7 @@ /** * @brief Count trailing zeros of a 64-bit integer. - * + * * @param [in] n The integer whose trailing zero count is to be computed. * @return If n != 0, returns trailing zero count; Else returns 64. */ @@ -29,7 +29,7 @@ static int gaICtz(uint64_t n); /** * @brief Count leading zeros of a 64-bit integer. - * + * * @param [in] n The integer whose leading zero count is to be computed. * @return If n != 0, returns leading zero count; Else returns 64. */ @@ -38,11 +38,11 @@ static int gaIClz(uint64_t n); /** * @brief Integer Modular Multiplication. - * + * * Computes - * + * * $$a*b \pmod m$$ - * + * * efficiently for 64-bit unsigned integers a, b, m. */ @@ -50,11 +50,11 @@ static uint64_t gaIMulMod (uint64_t a, uint64_t b, uint64_t m); /** * @brief Integer Modular Exponentiation. - * + * * Computes - * + * * $$x^a \pmod m$$ - * + * * efficiently for 64-bit unsigned integers x, a, m. */ @@ -108,11 +108,11 @@ static int gaICtz (uint64_t n){ return n ? __builtin_ctzll(n) : 64; #else int z; - + for(z=0;z<64;z++){ if((n>>z) & 1){break;} } - + return z; #endif } @@ -122,11 +122,11 @@ static int gaIClz (uint64_t n){ return n ? __builtin_clzll(n) : 64; #else int z; - + for(z=63;z>=0;z--){ if((n>>z) & 1){break;} } - + return 63-z; #endif } @@ -134,7 +134,7 @@ static int gaIClz (uint64_t n){ static uint64_t gaIMulMod (uint64_t a, uint64_t b, uint64_t m){ #if (__GNUC__ >= 4) && defined(__x86_64__) uint64_t r; - + asm( "mul %2\n\t" "div %3\n\t" @@ -142,7 +142,7 @@ static uint64_t gaIMulMod (uint64_t a, uint64_t b, uint64_t m){ : "a"(a), "r"(b), "r"(m) /* Inputs */ : "cc" ); - + return r; #elif (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6) /* Hardcore GCC 4.6+ optimization jazz */ @@ -150,44 +150,44 @@ static uint64_t gaIMulMod (uint64_t a, uint64_t b, uint64_t m){ #else const uint64_t TWOPOW32 = (uint64_t)1<<32; int i; - + a %= m; b %= m; - + if(m <= TWOPOW32){ /** * Fast path: When performing modulo arithmetic on values <= 2^32, * (a*b) % m gives the correct answer. */ - + return (a*b) % m; }else{ /** * Slow path: Have to simulate 128-bit arithmetic long division. */ - + uint64_t ah = a>>32; uint64_t al = (uint32_t)a; uint64_t bh = b>>32; uint64_t bl = (uint32_t)b; - + uint64_t ahbh = ah*bh; uint64_t ahbl = ah*bl; uint64_t albh = al*bh; uint64_t albl = al*bl; - + uint64_t md = ahbl+albh; - + uint64_t lo = albl + (md<<32); uint64_t hi = ahbh + (md>>32); - + /* Propagate carry-outs from `md` and `lo` into `hi` */ if(lo < albl){hi++;} if(md < ahbl){hi+=TWOPOW32;} - + /** * Begin 128-bit-by-64-bit remainder. - * + * * 1) Cut down `hi` mod `m`. This implements the first few iterations * of a shift-and-subtract loop, leaving only 64 iterations to go. * 2) Iterate 64 times: @@ -201,18 +201,18 @@ static uint64_t gaIMulMod (uint64_t a, uint64_t b, uint64_t m){ * order to bring back newHi within the range [0, m). * 3) The modulo is in hi. */ - + hi %= m; for(i=0;i<64;i++){ uint64_t newLo = (lo<<1); uint64_t newHi = (hi<<1) + (newLo m){newHi -= m;} - + hi = newHi; lo = newLo; } - + return hi; } #endif @@ -220,7 +220,7 @@ static uint64_t gaIMulMod (uint64_t a, uint64_t b, uint64_t m){ static uint64_t gaIPowMod (uint64_t x, uint64_t a, uint64_t m){ uint64_t r; - + /** * Special cases (order matters!): * - A modulo of 0 makes no sense and a modulo of 1 implies a return value @@ -230,13 +230,13 @@ static uint64_t gaIPowMod (uint64_t x, uint64_t a, uint64_t m){ * - An exponent of 1 requires a return value of x. * - An exponent of 2 can be handled by the modulo multiplication directly. */ - + if(m<=1){ return 0; } - + x %= m; - + if(a==0){ return 1; }else if(x<=1){ @@ -246,21 +246,21 @@ static uint64_t gaIPowMod (uint64_t x, uint64_t a, uint64_t m){ }else if(a==2){ return gaIMulMod(x,x,m); } - + /** * Otherwise, perform modular exponentiation by squaring. */ - + r = 1; while(a){ if(a&1){ r = gaIMulMod(r, x, m); } - + x = gaIMulMod(x, x, m); a >>= 1; } - + return r; } @@ -270,24 +270,24 @@ int gaIIsPrime (uint64_t n){ uint64_t r, d; const uint64_t WITNESSES[] = {2,3,5,7,11,13,17,19,23,29,31,37}; const int NUMWITNESSES = sizeof(WITNESSES)/sizeof(WITNESSES[0]); - - + + /** * Check if it is 2, the oddest prime. */ - + if(n==2){return 1;} - + /** * Check if it is an even integer. */ - + if((n&1) == 0){return 0;} - + /** * For small integers, read directly the answer in a table. */ - + if(n<256){ return "nnyynynynnnynynnnynynnnynnnnnyny" "nnnnnynnnynynnnynnnnnynnnnnynynn" @@ -298,20 +298,20 @@ int gaIIsPrime (uint64_t n){ "nynnnynynnnnnnnnnnnynnnnnnnnnnny" "nnnynynnnynnnnnynynnnnnnnnnynnnn"[n] == 'y'; } - + /** * Test small prime factors. */ - + hasNoSmallFactors = n%3 && n%5 && n%7 && n%11 && n%13; hasSmallFactors = !hasNoSmallFactors; if(hasSmallFactors){ return 0; } - + /** * Otherwise proceed to the Miller-Rabin test. - * + * * The Miller-Rabin test uses integer "witnesses" in an attempt at * proving the number composite. Should it fail to prove an integer * composite, it reports the number as "probably prime". However, if @@ -320,33 +320,33 @@ int gaIIsPrime (uint64_t n){ * 2 to 37 in order to ensure the correctness of the identifications for * integers under 2^64. */ - + r = gaICtz(n-1); d = (n-1)>>r; - + /* For each witness... */ for(i=0;i 0 && maxN < n)){ return 0; } - + /** * Handle special cases of n = 0,1,2. */ - + if(n<=2){ gaIFLInit(fl); gaIFLAddFactors(fl, n, 1); return 1; } - + /** * Magic-value arguments interpreted and canonicalized. */ - + if(maxN == (uint64_t)-1 || gaIClz(maxN) < gaIClz(n)){ /** * Either we are allowed unlimited growth of n, or the slack space @@ -404,71 +404,71 @@ int gaIFactorize (uint64_t n, uint64_t maxN, uint64_t k, ga_factor_list* fl * automatically satisfy the most stringent possible smoothness * constraint. */ - + return gaIFactorizeNextPow2(n, fl); }else if(maxN == 0){ /** * We are asked for a strict factoring. */ - + maxN = n; } - + if(k == 0 || k >= n){ /** * We want no k-smoothness constraint. */ - + k = n; } - - + + /** * Master loop. */ - + for(i=n; i <= maxN; i++){ /** * Do not manipulate the loop index! * Initial subfactor to cut down is x=i. */ - + x = i; gaIFLInit(fl); - + /** * Subfactorization always begins with an attempt at an initial * cut-down by factors of 2. Should this result in a 1 (which isn't * technically prime, but indicates a complete factorization), we * report success. */ - + subfactorize: gaIFLAddFactors(fl, 2, gaICtz(x)); x >>= gaICtz(x); f = 3; - + /** * Primality test. - * + * * If the remaining factor x is a prime number, it's decision time. One * of two things is true: - * + * * 1) We have a smoothness constraint k and x is <= than it, or we * don't have a smoothness constraint at all (k==n). Both cases are * covered by checking x<=k. - * + * * In this case we add x as the last factor to the factor list and * return affirmatively. - * + * * 2) We have a smoothness constraint and x>k. - * + * * In this case we have to increment x and begin anew the * sub-factorization. This may cause us to fail out of factorizing * the current i, by exceeding our slack limit. If this happens we * abort the factorization rooted at i and move to the next i. */ - + primetest: if(x==1 || gaIIsPrime(x)){ if(x<=k){ @@ -484,16 +484,16 @@ int gaIFactorize (uint64_t n, uint64_t maxN, uint64_t k, ga_factor_list* fl } } } - + /** * Composite number handler. - * + * * We continue by trying to cut down x by factors of 3+. Should a trial * division by a factor f succeed, all powers of f are factored out of * x and once f no longer divides x evenly, a new primality test is * run. The primality test will be invoked at most 15 times from this loop. */ - + for(;f<=k && f*f<=x && f<=0xFFFFFFFFU;f+=2){/* Overflow-safe f*f */ if(x%f == 0){ c = 0; @@ -501,17 +501,17 @@ int gaIFactorize (uint64_t n, uint64_t maxN, uint64_t k, ga_factor_list* fl x /= f; c++; }while(x%f == 0); - + gaIFLAddFactors(fl, f, c); - + goto primetest; } } - + /* Check before next iteration for 64-bit integer overflow. */ nextI: if(i == 0xFFFFFFFFFFFFFFFF){break;} } - + /* Failed to factorize. */ return 0; } @@ -525,10 +525,10 @@ static int gaIFactorizeNextPow2(uint64_t n, ga_factor_list* fl){ n |= n >> 16; n |= n >> 32; n++; - + gaIFLInit(fl); gaIFLAddFactors(fl, 2, gaICtz(n)); - + return 1; } @@ -542,37 +542,37 @@ int gaIFLFull(ga_factor_list* fl){ int gaIFLAddFactors(ga_factor_list* fl, uint64_t f, int p){ int i; - + /** * Fast case: We're adding 0 powers of f, or any powers of 1. The * value of the factor list (and the integer it represents) is thus * unchanged. */ - + if(p == 0 || f == 1){ return 1; } - + /** * Otherwise, the factor list has to change. We scan linearly the factor * list for either a pre-existing spot or an insertion spot. Scanning * linearly over a 15-element array is faster and less complex than binary * search. */ - + for(i=0;id;i++){ if(fl->f[i] == f){ /** * Factor is already in list. */ - + fl->p[i] += p; if(fl->p[i] == 0){ /** * We removed all factors f. Bump leftwards the remainder to * maintain sorted order. */ - + memmove(&fl->f[i], &fl->f[i+1], sizeof(fl->f[i])*(fl->d-i)); memmove(&fl->p[i], &fl->p[i+1], sizeof(fl->p[i])*(fl->d-i)); fl->d--; @@ -581,12 +581,12 @@ int gaIFLAddFactors(ga_factor_list* fl, uint64_t f, int p){ }else if(fl->f[i] > f){ /* Inject the factor at this place in order to keep list sorted, if we have the capacity. */ - + if(gaIFLFull(fl)){ /* We can't bump the list rightwards, it's full already! */ return 0; } - + memmove(&fl->f[i+1], &fl->f[i], sizeof(fl->f[i])*(fl->d-i)); memmove(&fl->p[i+1], &fl->p[i], sizeof(fl->p[i])*(fl->d-i)); fl->f[i] = f; @@ -595,15 +595,15 @@ int gaIFLAddFactors(ga_factor_list* fl, uint64_t f, int p){ return 1; } } - + /** * We looked at every factor in the list and f is strictly greater than * all of them. - * + * * If the list is full, we cannot insert f, but if it isn't, we can simply * tack it at the end. */ - + if(gaIFLFull(fl)){ return 0; }else{ @@ -616,26 +616,26 @@ int gaIFLAddFactors(ga_factor_list* fl, uint64_t f, int p){ int gaIFLGetFactorPower(ga_factor_list* fl, uint64_t f){ int i; - + for(i=0;id;i++){ if(fl->f[i] == f){ return fl->p[i]; } } - + return 0; } uint64_t gaIFLGetProduct(const ga_factor_list* fl){ uint64_t p = 1; int i, j; - + for(i=0;id;i++){ for(j=0;jp[i];j++){ p *= fl->f[i]; } } - + return p; } @@ -650,20 +650,20 @@ uint64_t gaIFLGetSmallestFactor(const ga_factor_list* fl){ static uint64_t gaIFLGetProductv(int n, const ga_factor_list* fl){ uint64_t p = 1; int i; - + for(i=0;i 0){ hasFactors = 1; @@ -674,16 +674,16 @@ static uint64_t gaIFLGetGreatestFactorv(int n, const ga_factor_list* fl, int* id } } } - + return hasFactors ? f : 1; } static uint64_t gaIFLGetSmallestFactorv(int n, const ga_factor_list* fl, int* idx){ uint64_t f = -1, currF; int i, hasFactors=0; - + if(idx){*idx = 0;} - + for(i=0;i 0){ hasFactors = 1; @@ -694,48 +694,26 @@ static uint64_t gaIFLGetSmallestFactorv(int n, const ga_factor_list* fl, int* id } } } - + return hasFactors ? f : 1; } -int gaIFLsnprintf(char* str, size_t size, const ga_factor_list* fl){ - int i, j; - - int total = 0; - size_t left = size; - char* ptr = size ? str : NULL; - - /* Loop over all factors and spit them out. */ - for(i=0;id;i++){ - for(j=0;jp[i];j++){ - total += snprintf(ptr, left, "%llu*", (unsigned long long)fl->f[i]); - if(ptr){ - left -= strlen(ptr); - ptr += strlen(ptr); - } - } - } - - /* If no factors were printed, print 1. */ - if(total == 0){ - total += snprintf(ptr, left, "1*"); - if(ptr){ - left -= strlen(ptr); - ptr += strlen(ptr); - } - } - - /* Terminate buffer ('*' -> '\0') and deduct one character. */ - total--; - if(str && size > 0){ - if(total >= size){ - str[size-1] = '\0'; - }else{ - str[total] = '\0'; - } - } - - return total; +void gaIFLappend(strb *sb, const ga_factor_list* fl){ + int i, j; + /* Loop over all factors and spit them out. */ + for (i = 0; i < fl->d; i++) { + for (j = 0; j < fl->p[i]; j++) { + strb_appendf(sb, "%llu*", (unsigned long long)fl->f[i]); + } + } + + /* If no factors were printed, print 1. */ + if (i == 0 && j == 0) { + strb_appendf(sb, "1*"); + } + + /* Deduct final '*'. */ + sb->l -= 1; } void gaIFLSchedule(const int n, @@ -749,38 +727,38 @@ void gaIFLSchedule(const int n, /** * If we have zero dimensions, the scheduling job is easy. */ - + if(n<=0){return;} - + /** * First, we move factors from factBS[i] and factGS[i] to factCS[i], in * order of largest to smallest, until their product is at or below * maxBind[i] and maxGind[i] respectively. */ - + gaIFLScheduleSatisfyInd(n, factBS, factCS, maxBind); gaIFLScheduleSatisfyInd(n, factGS, factCS, maxGind); - + /** * Then we move out more factors from factBS[i] and factGS[i], in order of * smallest to largest, until their common product is at or below maxBtot * and maxGtot respectively. */ - + gaIFLScheduleSatisfyTot(n, factBS, factCS, maxBtot); gaIFLScheduleSatisfyTot(n, factGS, factCS, maxGtot); - + /** * At this point, the scheduling is guaranteed to be valid, but may be * nowhere close to optimal. - * + * * So we start moving in factors from factCS[i] to factBS[i], in order of * largest to smallest, while remaining below maxBtot and maxBind[i]. - * + * * Lastly, we move in factors from factCS[i] to factBG[i], in order of * largest to smallest, while remaining below maxGtot and maxGind[i]. */ - + gaIFLScheduleOpt(n, factCS, factBS, maxBtot, maxBind); gaIFLScheduleOpt(n, factCS, factGS, maxGtot, maxGind); } @@ -791,7 +769,7 @@ static void gaIFLScheduleSatisfyInd(const int n, const uint64_t* maxInd){ int i; uint64_t f, p; - + for(i=0;i maxTot){ f = gaIFLGetSmallestFactorv(n, from, &a); c = gaIFLGetFactorPower (from+a, f); - + for(i=c-1;i>=0 && p>maxTot;i--){ p /= f; gaIFLAddFactors(from+a, f, -1); @@ -840,14 +818,14 @@ static void gaIFLScheduleOpt(const int n, #else uint64_t pInd[n]; #endif - + /* Muzzle compiler about a random function being unused. */ (void)gaIFLGetGreatestFactorv; - + /** * Check whether optimization is possible. */ - + for(i=0;i=0;j--){ currF = from[i].f[j]; - + if(currF <= maxFTot && currF <= maxFInd && currF >= f){ f = currF; k = i; @@ -884,18 +862,18 @@ static void gaIFLScheduleOpt(const int n, } } } - + if(k == -1){ break; } - + gaIFLAddFactors(from+k, f, -1); gaIFLAddFactors(to +k, f, +1); pInd[k] *= f; pTot *= f; maxFTot = maxTot/pTot; }while(maxFTot>1 && f>1); - + #if GA_USING_MALLOC_FOR_VLA free(pInd); #endif diff --git a/src/util/integerfactoring.h b/src/util/integerfactoring.h index c6c3d6cd04..7d2339c6bb 100644 --- a/src/util/integerfactoring.h +++ b/src/util/integerfactoring.h @@ -7,6 +7,8 @@ #include #include +#include "util/strb.h" + /* Defines */ @@ -29,16 +31,16 @@ typedef struct ga_factor_list_ ga_factor_list; /** * @brief The GA_FACTOR_LIST struct. - * + * * Contains the list of distinct prime factors of a 64-bit unsigned integer, as * well as the powers of those factors. - * + * * There can be at most 15 such distinct factors, since the product of the * first 16 primes (2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53) exceeds * the maximum unsigned number of 2^64-1. Moreover, there can be at most 63 * factors all together, since 2^64 exceeds 2^64-1, so only an 8-bit number is * required to store the powers. - * + * * The 15th (last) element of the factor list is always 0 and has power 0, * and serves as a sort of sentinel. */ @@ -55,10 +57,10 @@ struct ga_factor_list_{ /** * @brief Checks whether an integer is prime. - * + * * @param [in] n The integer whose primality is to be checked. * @return 1 if prime; 0 if not prime. - * + * * NB: This is *not* a probabilistic primality checker. For all integers it can * be given as input, it will correctly report "prime" or "composite". * NB: Internally, this function uses the Miller-Rabin test, which *is* @@ -67,9 +69,9 @@ struct ga_factor_list_{ * Miller-Rabin "witnesses", which ensures that there are no strong * probable primes equal to or below 2^64-1 (the size of the input * argument). This set of witnesses is - * + * * $$a = 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, and 37$$ - * + * * See https://oeis.org/A014233 */ @@ -78,28 +80,28 @@ int gaIIsPrime(uint64_t n); /** * @brief Factorize a positive integer into a list of factors satisfying * certain properties. - * + * * The function factorizes a 64-bit, positive integer into a list of factors. * This factorization can be made "approximate"; That is, the product of the * factors returned can be slightly greater than the input number. The * maximum increase is controlled by a "slack" parameter maxN, as follows: - * + * * $$\texttt{n} \le \prod(\mathrm{fact}(\texttt{n}) \le \texttt{maxN}$$ - * + * * The advantage of offering some slack to the factorizer is that in return, * the factorizer may succeed in outputting a factorization with smaller * factors. The maxN slack parameter must be 0 or be greater than or equal to * n, but it is useless to set it beyond twice the value of n. - * + * * When maxN is equal to -1 (2^64 - 1), or is greater than or equal to 2n, * there is a guarantee that there exists a power of two that lies between n * and 2n. Since this factorization involves only powers of the smallest prime * (2), it is a valid factorization under any valid k-smoothness constraint, * and so will be returned. - * + * * When maxN is equal to 0 or n (no increase in value allowed), this implies * that an exact factoring is requested. - * + * * The factorization can also be constrained by a (k)-smoothness constraint. * A k-smooth number n has no prime factors greater than k. If the factorizer * is asked to factor with k-smoothness a number with prime factors greater @@ -107,11 +109,11 @@ int gaIIsPrime(uint64_t n); * number that is k-smooth and return that number's factoring. With maxN == n * and a k-smoothness constraint, this function reports whether or not the * number is k-smooth. - * + * * When k is equal to 0, equal to -1 (2^64 - 1), or is greater than or equal * to n, no k-smoothness constraints are imposed. An exact factoring is * required. - * + * * @param [in] n The integer to be factorized. Must be >0. * @param [in] maxN The "slack" parameter. The factor list returned will * not have a product that exceeds this number. @@ -131,7 +133,7 @@ int gaIFactorize(uint64_t n, uint64_t maxN, uint64_t k, ga_factor_list* fl) /** * @brief Initialize a factors list to all-factors- and all-powers-zero. - * + * * Such a factors list represents 1, since 0^0 = 1. */ @@ -140,7 +142,7 @@ void gaIFLInit(ga_factor_list* fl); /** * @brief Reports whether another *distinct* factor can be added to the factor * list safely. - * + * * @return Returns zero if there are less than 15 distinct factors in the list * and non-zero otherwise. */ @@ -149,13 +151,13 @@ int gaIFLFull(ga_factor_list* fl); /** * @brief Add a factor f with power p to the factor list. - * + * * If factor f was already present in the factor list, increments * the corresponding power by p. Otherwise, adds the new factor f to * the list, if there is still space, and sets the power to p. - * + * * Maintains factor list in sorted order. - * + * * @return Non-zero if factor successfully added; Zero otherwise. */ @@ -163,7 +165,7 @@ int gaIFLAddFactors(ga_factor_list* fl, uint64_t f, int p); /** * @brief Get the power of a given factor within a factor list. - * + * * @return The number of times a factor occurs within the current * factorization. If it does not occur, return 0. */ @@ -189,25 +191,20 @@ uint64_t gaIFLGetGreatestFactor(const ga_factor_list* fl); uint64_t gaIFLGetSmallestFactor(const ga_factor_list* fl); /** - * @brief Print out the factor list in a human-readable form, snprintf()-style. - * - * @param [out] str A string into which to print out the factor list. If the - * factor list is a result of gaIFactorize(), then the - * maximum length of buffer required is 128 bytes. - * If str is NULL, nothing is printed. - * @param [in] size The maximum number of bytes written, including the - * terminating NUL (\0) character. - * @param [in] fl The factor list to be printed. - * @return The number of characters that would have been printed - * out, assuming an unbounded, non-NULL buffer. + * @brief Print out the factor list in a human-readable form. + * + * @param [out] sb A string into which to print out the factor list. If the + * factor list is a result of gaIFactorize(), then the + * maximum length of buffer required is 128 bytes. + * @param [in] fl The factor list to be printed. */ -int gaIFLsnprintf(char* str, size_t size, const ga_factor_list* fl); +void gaIFLsnprintf(strb *sb, const ga_factor_list* fl); /** * @brief Schedule block size, grid size and what's left over that fits in * neither, which will be called "chunk" size, subject to constraints. - * + * * @param [in] n Number of dimensions of the problem. The arrays * maxBind, maxGind, factBS, factGS, factCS must have * n elements.