Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add fermats little theorem #809

Closed

Conversation

saahil-mahato
Copy link

@saahil-mahato saahil-mahato commented Oct 6, 2024

Description

Fermat Primality Test Implementation

This PR introduces an implementation of the Fermat Primality Test in Rust. The algorithm leverages Fermat's Little Theorem, which states that if ( p ) is a prime number, then for any integer ( a ) such that ( 1 < a < p - 1 ), it holds that:

a^(p−1) ≡ 1 (mod p)

Key Features:

  • Modular Exponentiation: Efficient computation of ( a^{(p-1)} \mod p ) is performed using a helper function to handle large numbers without overflow.
  • Probabilistic Approach: The algorithm allows for multiple iterations (k tests) with randomly selected bases to increase the reliability of the primality check.
  • Composite Detection: While it identifies prime numbers effectively, the implementation also recognizes that some composite numbers, known as Carmichael numbers, can pass the test under certain conditions.

Test Cases:

  • The PR includes comprehensive unit tests for various scenarios, including known prime numbers, composite numbers, small integers, large numbers, and special cases like Carmichael numbers.

This implementation provides a fast, probabilistic approach to primality testing, making it suitable for applications in cryptography and numerical analysis.

Type of change

Please delete options that are not relevant.

  • New feature (non-breaking change which adds functionality)

Checklist:

  • I ran bellow commands using the latest version of rust nightly.
  • I ran cargo clippy --all -- -D warnings just before my last commit and fixed any issue that was found.
  • I ran cargo fmt just before my last commit.
  • I ran cargo test just before my last commit and all tests passed.
  • I added my algorithm to the corresponding mod.rs file within its own folder, and in any parent folder(s).
  • I added my algorithm to DIRECTORY.md with the correct link.
  • I checked COUNTRIBUTING.md and my code follows its guidelines.

@codecov-commenter
Copy link

codecov-commenter commented Oct 6, 2024

Codecov Report

Attention: Patch coverage is 96.00000% with 1 line in your changes missing coverage. Please review.

Project coverage is 95.36%. Comparing base (bc8d6fa) to head (dfcdea6).
Report is 8 commits behind head on master.

Files with missing lines Patch % Lines
src/math/fermats_little_theorem.rs 96.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #809      +/-   ##
==========================================
+ Coverage   95.32%   95.36%   +0.04%     
==========================================
  Files         310      312       +2     
  Lines       22484    22698     +214     
==========================================
+ Hits        21433    21647     +214     
  Misses       1051     1051              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

src/math/fermats_little_theorem.rs Outdated Show resolved Hide resolved
src/math/fermats_little_theorem.rs Outdated Show resolved Hide resolved
let carmichael_numbers = vec![561, 1105, 1729, 2465, 2821, 6601];
for &n in &carmichael_numbers {
fermats_little_theorem(n, 10);
// Skip assertion for carmichael numbers
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do you skip the assertion here?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Its because carmichael numbers can be true or false as this is a probabilistic test. I will use a constant seed so that tests don't fail.

@saahil-mahato
Copy link
Author

@vil02 I have resolved the comments. Please review and let me know if anything is missing.

Comment on lines +70 to +135
macro_rules! test_cases {
($(
$test_name:ident: [
$(($n:expr, $a:expr, $expected:expr)),+ $(,)?
]
),+ $(,)?) => {
$(
#[test]
fn $test_name() {
$(
assert_eq!(
fermats_little_theorem($n, $a),
$expected,
"Failed for n={}, a={}",
$n,
$a
);
)+
}
)+
};
}

test_cases! {
// Test cases for prime numbers
test_prime_numbers: [
(5, 10, true),
(13, 10, true),
(101, 10, true),
(997, 10, true),
(7919, 10, true),
],

// Test cases for composite numbers
test_composite_numbers: [
(4, 10, false),
(15, 10, false),
(100, 10, false),
(1001, 10, false),
],

// Test cases for small numbers
test_small_numbers: [
(1, 10, false),
(2, 10, true),
(3, 10, true),
(0, 10, false),
],

// Test cases for large numbers
test_large_numbers: [
(104729, 10, true),
(104730, 10, false),
],

// Test cases for Carmichael numbers
test_carmichael_numbers: [
(561, 10, false),
(1105, 10, false),
(1729, 10, false),
(2465, 10, false),
(2821, 10, false),
(6601, 10, true),
(8911, 10, false),
],
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not something like that:

Suggested change
macro_rules! test_cases {
($(
$test_name:ident: [
$(($n:expr, $a:expr, $expected:expr)),+ $(,)?
]
),+ $(,)?) => {
$(
#[test]
fn $test_name() {
$(
assert_eq!(
fermats_little_theorem($n, $a),
$expected,
"Failed for n={}, a={}",
$n,
$a
);
)+
}
)+
};
}
test_cases! {
// Test cases for prime numbers
test_prime_numbers: [
(5, 10, true),
(13, 10, true),
(101, 10, true),
(997, 10, true),
(7919, 10, true),
],
// Test cases for composite numbers
test_composite_numbers: [
(4, 10, false),
(15, 10, false),
(100, 10, false),
(1001, 10, false),
],
// Test cases for small numbers
test_small_numbers: [
(1, 10, false),
(2, 10, true),
(3, 10, true),
(0, 10, false),
],
// Test cases for large numbers
test_large_numbers: [
(104729, 10, true),
(104730, 10, false),
],
// Test cases for Carmichael numbers
test_carmichael_numbers: [
(561, 10, false),
(1105, 10, false),
(1729, 10, false),
(2465, 10, false),
(2821, 10, false),
(6601, 10, true),
(8911, 10, false),
],
}
macro_rules! test_fermats_little_theorem {
($($name:ident: $inputs:expr,)*) => {
$(
#[test]
fn $name() {
let (p, k, expected) = $inputs;
assert_eq!(fermats_little_theorem(p, k), expected);
}
)*
};
}
test_fermats_little_theorem! {
prime_2: (2, 10, true),
prime_3: (3, 10, true),
prime_5: (5, 10, true),
prime_13: (13, 10, true),
prime_101: (101, 10, true),
prime_997: (997, 10, true),
prime_7919: (7919, 10, true),
prime_104729: (104729, 10, true),
composite_0: (0, 10, false),
composite_1: (1, 10, false),
composite_4: (4, 10, false),
composite_15: (15, 10, false),
composite_100: (100, 10, false),
composite_1001: (1001, 10, false),
composite_104730: (104730, 10, false),
carmichael_561: (561, 10, false),
carmichael_1105: (1105 , 10, false),
carmichael_1729: (1729, 10, false),
carmichael_2465: (2465, 10, false),
carmichael_2821: (2821, 10, false),
carmichael_6601: (6601, 10, true),
carmichael_8911: (8911, 10, false),
}

/// Fermat primality test for every `a` such that `gcd(a, n) = 1`. Therefore, Carmichael numbers can
/// fool Fermat's test into incorrectly identifying them as primes. The first few Carmichael numbers
/// are 561, 1105, 1729, 2465, 2821, and 6601.
pub fn fermats_little_theorem(p: i64, k: i32) -> bool {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • please change the type of p to be u64. In order to use modular_exponential you can just cast it,
  • why not to add seed being Option<u64> - if it would be None, the seed would be selected at random,
  • consider changing the return type to some enum with values Composite and ProbablyPrime.

Comment on lines +127 to +131
(561, 10, false),
(1105, 10, false),
(1729, 10, false),
(2465, 10, false),
(2821, 10, false),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is something what I do not understand: how this function could return false for these numbers? By the definition the result should be true for them.

@saahil-mahato saahil-mahato closed this by deleting the head repository Oct 27, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants