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
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
//! # Factorizing integers
use gcd::Gcd;

use crate::integer::factorization::prime::Prime;
use crate::integer::factorization::prime::primes::SMALL_ODD_PRIMES;
use crate::non_zero::NonZeroSign;
use crate::non_zero::NonZeroSigned;
use crate::traits::factorization::{NonZeroFactorizable, NonZeroFactorization};

pub mod prime;

impl NonZeroFactorizable for i32 {
    type Factor = u32;
    // TODO(CORRECTNESS): Consider making this type unsigned
    type Power = i8;

    fn factorize(&self) -> NonZeroFactorization<Self::Factor, Self::Power> {
        let sign = NonZeroSigned::signum(self);
        let NonZeroFactorization {
            factors, ..
        } = self.unsigned_abs().factorize();
        NonZeroFactorization { sign, factors }
    }
}

impl NonZeroFactorizable for u32 {
    type Factor = u32;
    // TODO(CORRECTNESS): Consider making this type unsigned
    type Power = i8;

    fn factorize(&self) -> NonZeroFactorization<Self::Factor, Self::Power> {
        debug_assert_ne!(*self, 0);

        let mut x = self.clone();
        let mut unsorted_factors = Vec::with_capacity(32);

        while x % 2 == 0 {
            x /= 2;
            unsorted_factors.push(2);
        }

        'odd_trial_division: {
            // smallest
            for divisor in SMALL_ODD_PRIMES {
                while x % divisor as u32 == 0 {
                    x /= divisor as u32;
                    unsorted_factors.push(divisor as u32);
                }

                if x == 1 {
                    break 'odd_trial_division;
                }
            }
            // small
            let first = *SMALL_ODD_PRIMES.last().unwrap() as u32 + 2;
            let last = 2_u32.pow(32 / 2);
            let mut sqrt = ((x as f64).sqrt() + 2_f64) as u32;
            for divisor in (first..last).step_by(2) {
                while x % divisor == 0 {
                    x /= divisor;
                    sqrt = ((x as f64).sqrt() + 2_f64) as u32;
                    unsorted_factors.push(divisor);
                }

                if x == 1 {
                    break 'odd_trial_division;
                } else if divisor > sqrt {
                    unsorted_factors.push(x);
                    break 'odd_trial_division;
                }
            }
        }

        // Aggregate the factors
        let mut factors = Vec::with_capacity(16);
        for factor in unsorted_factors {
            if let Some((existing_factor, count)) = factors.last_mut() {
                if *existing_factor == factor {
                    *count += 1;
                    continue;
                }
            }

            factors.push((factor, 1));
        }

        NonZeroFactorization { sign: NonZeroSign::Positive, factors }
    }
}

impl NonZeroFactorizable for i64 {
    type Factor = u64;
    // TODO(CORRECTNESS): Consider making this type unsigned
    type Power = i8;

    fn factorize(&self) -> NonZeroFactorization<Self::Factor, Self::Power> {
        let sign = NonZeroSigned::signum(self);
        let NonZeroFactorization {
            factors, ..
        } = self.unsigned_abs().factorize();
        NonZeroFactorization { sign, factors }
    }
}

impl NonZeroFactorizable for u64 {
    type Factor = u64;
    // TODO(CORRECTNESS): Consider making this type unsigned
    type Power = i8;

    fn factorize(&self) -> NonZeroFactorization<Self::Factor, Self::Power> {
        debug_assert_ne!(*self, 0);

        let mut x = self.clone();
        let mut unsorted_factors = Vec::with_capacity(64);

        // Trial division
        // 2
        while x % 2 == 0 {
            x /= 2;
            unsorted_factors.push(2);
        }
        'odd: {
            // smallest
            for divisor in SMALL_ODD_PRIMES {
                while x % divisor as u64 == 0 {
                    x /= divisor as u64;
                    unsorted_factors.push(divisor as u64);
                }

                if x == 1 {
                    break 'odd;
                }
            }
            // small
            let first = *SMALL_ODD_PRIMES.last().unwrap() as u64 + 2;
            let last = 500_000;
            // TODO(PERFORMANCE): How far should this loop go?
            let mut sqrt = ((x as f64).sqrt() + 2_f64) as u64;
            for divisor in (first..last).step_by(2) {
                while x % divisor == 0 {
                    x /= divisor;
                    sqrt = ((x as f64).sqrt() + 2_f64) as u64;
                    unsorted_factors.push(divisor);
                }

                if x == 1 {
                    break 'odd;
                } else if divisor > sqrt {
                    // Checked enough, must be prime
                    unsorted_factors.push(x);
                    break 'odd;
                }
            }

            // Prime test and Pollard's rho
            rho_loop(x, &mut unsorted_factors);
        }

        // Sort and aggregate the factors
        unsorted_factors.sort();
        let mut factors = Vec::with_capacity(16);
        for factor in unsorted_factors {
            if let Some((existing_factor, count)) = factors.last_mut() {
                if *existing_factor == factor {
                    *count += 1;
                    continue;
                }
            }

            factors.push((factor, 1));
        }

        NonZeroFactorization { sign: NonZeroSign::Positive, factors }
    }
}

// TODO(PERFORMANCE): How long should this be tried?
const RHO_BASE_LIMIT: u64 = 20;

fn rho_loop(mut x: u64, factors: &mut Vec<u64>) {
    debug_assert_ne!(x, 0);

    let mut e = 2;
    while x > 1 {
        if x.is_prime() || e == RHO_BASE_LIMIT {
            factors.push(x);
            break;
        }

        match rho(x, e) {
            None | Some(1) => {
                // TODO(PERFORMANCE): Odd values only?
                e += 1;
            }
            Some(factor) => {
                if factor.is_prime() {
                    factors.push(factor);
                } else {
                    // TODO(PERFORMANCE): Should the `e` variable be passed to the inner call?
                    rho_loop(factor, factors);
                }
                x /= factor;
            }
        }
    }
}

/// Pollard's rho function generates a divisor.
///
/// Up to minor adaptions, this code is from the reikna repository developed by Phillip Heikoop.
pub fn rho(value: u64, entropy: u64) -> Option<u64> {
    debug_assert_ne!(value, 0);
    debug_assert_ne!(value, 1);
    debug_assert_ne!(value, 2);

    let entropy = entropy.wrapping_mul(value);
    let c = entropy & 0xff;
    let u = entropy & 0x7f;

    let mut r: u64 = 1;
    let mut q: u64 = 1;
    let mut y: u64 = entropy & 0xf;

    let mut factor = 1;

    let mut y_old = 0;
    let mut x = 0;

    let f = |x: u64| (x.wrapping_mul(x) + c) % value;

    while factor == 1 {
        x = y;

        for _ in 0..r {
            y = f(y);
        }

        let mut k = 0;
        while k < r && factor == 1 {
            y_old = y;

            for _ in 0..u64::min(u, r - k) {
                y = f(y);

                if x > y {
                    q = q.wrapping_mul(x - y) % value;
                } else {
                    q = q.wrapping_mul(y - x) % value;
                }
            }

            factor = Gcd::gcd(q, value);
            k += u;
        }

        r *= 2;
    }


    while factor == value || factor <= 1 {
        y_old = f(y_old);

        if x > y_old {
            factor = Gcd::gcd(x - y_old, value);
        } else if x < y_old {
            factor = Gcd::gcd(y_old - x, value);
        } else {
            // the algorithm has failed for this entropy,
            // return the factor as-is
            return None;
        }
    }

    Some(factor)
}

#[cfg(test)]
mod test {
    use crate::non_zero::NonZeroSign;
    use crate::traits::factorization::{NonZeroFactorizable, NonZeroFactorization};

    #[test]
    fn test_factorize_one() {
        assert_eq!(1_u64.factorize(), NonZeroFactorization { sign: NonZeroSign::Positive, factors: vec![]});
    }

    #[test]
    fn test_factorize_two_powers() {
        assert_eq!(
            2_u64.factorize(),
            NonZeroFactorization { sign: NonZeroSign::Positive, factors: vec![(2, 1)] },
        );
        assert_eq!(
            4_u64.factorize(),
            NonZeroFactorization { sign: NonZeroSign::Positive, factors: vec![(2, 2)] },
        );
        assert_eq!(
            2_u64.pow(16).factorize(),
            NonZeroFactorization { sign: NonZeroSign::Positive, factors: vec![(2, 16)] },
        );
    }

    #[test]
    fn test_factorize_three_powers() {
        assert_eq!(
            3_u64.factorize(),
            NonZeroFactorization { sign: NonZeroSign::Positive, factors: vec![(3, 1)] },
        );
        assert_eq!(
            9_u64.factorize(),
            NonZeroFactorization { sign: NonZeroSign::Positive, factors: vec![(3, 2)] },
        );
        assert_eq!(
            3_u64.pow(16).factorize(),
            NonZeroFactorization { sign: NonZeroSign::Positive, factors: vec![(3, 16)] },
        );
    }

    #[test]
    fn test_factorize_mixed() {
        assert_eq!(
            6_u64.factorize(),
            NonZeroFactorization { sign: NonZeroSign::Positive, factors: vec![(2, 1), (3, 1)] },
        );
        assert_eq!(
            36_u64.factorize(),
            NonZeroFactorization { sign: NonZeroSign::Positive, factors: vec![(2, 2), (3, 2)] },
        );
        assert_eq!(
            6_u64.pow(16).factorize(),
            NonZeroFactorization { sign: NonZeroSign::Positive, factors: vec![(2, 16), (3, 16)] },
        );
    }

    #[test]
    fn test_factorize_large_prime() {
        let prime = 2_u64.pow(36) - 5;
        assert_eq!(
            prime.factorize(),
            NonZeroFactorization { sign: NonZeroSign::Positive, factors: vec![(prime, 1)] },
        );
        let prime = 2_u64.pow(60) - 93;
        assert_eq!(
            prime.factorize(),
            NonZeroFactorization { sign: NonZeroSign::Positive, factors: vec![(prime, 1)] },
        );
        let prime = 2_u64.pow(53) - 111;
        assert_eq!(
            prime.factorize(),
            NonZeroFactorization { sign: NonZeroSign::Positive, factors: vec![(prime, 1)] },
        );
    }

    #[test]
    fn test_factorize_large_composite_u64() {
        let composite = 2_u64.pow(36) - 7;
        assert_eq!(
            composite.factorize(),
            NonZeroFactorization { sign: NonZeroSign::Positive, factors: vec![(3, 1), (22906492243, 1)] },
        );
        let composite = 2_u64.pow(60) - 95;
        assert_eq!(
            composite.factorize(),
            NonZeroFactorization { sign: NonZeroSign::Positive, factors: vec![(3457, 1), (6203, 1), (53764867411, 1)] },
        );
        let composite = 2_u64.pow(53) - 113;
        assert_eq!(
            composite.factorize(),
            NonZeroFactorization { sign: NonZeroSign::Positive, factors: vec![(3, 2), (43, 1), (642739, 1), (36211303, 1)] },
        );
    }

    #[test]
    fn test_factorize_large_composite_i64() {
        let composite = 2_i64.pow(36) - 7;
        assert_eq!(
            composite.factorize(),
            NonZeroFactorization { sign: NonZeroSign::Positive, factors: vec![(3, 1), (22906492243, 1)] },
        );
        let composite = 2_i64.pow(60) - 95;
        assert_eq!(
            composite.factorize(),
            NonZeroFactorization { sign: NonZeroSign::Positive, factors: vec![(3457, 1), (6203, 1), (53764867411, 1)] },
        );
        let composite = 2_i64.pow(53) - 113;
        assert_eq!(
            composite.factorize(),
            NonZeroFactorization { sign: NonZeroSign::Positive, factors: vec![(3, 2), (43, 1), (642739, 1), (36211303, 1)] },
        );
    }
}