| 1 | 1 | def encode(plain_text: str, a: int, b: int) -> str: |
| 2 | pass | |
| 2 | m = 26 | |
| 3 | ||
| 4 | # Check if a and m are coprime | |
| 5 | if gcd(a, m) != 1: | |
| 6 | raise ValueError("a and m must be coprime.") | |
| 7 | ||
| 8 | result = [] | |
| 9 | for char in plain_text: | |
| 10 | if char.isalpha(): | |
| 11 | # Convert to lowercase and get index | |
| 12 | i = ord(char.lower()) - ord('a') | |
| 13 | # Apply encryption formula | |
| 14 | encrypted_index = (a * i + b) % m | |
| 15 | # Convert back to character | |
| 16 | result.append(chr(encrypted_index + ord('a'))) | |
| 17 | elif char.isdigit(): | |
| 18 | result.append(char) | |
| 19 | ||
| 20 | # Group into chunks of 5 | |
| 21 | cipher_text = ''.join(result) | |
| 22 | grouped = ' '.join([cipher_text[i:i+5] for i in range(0, len(cipher_text), 5)]) | |
| 23 | return grouped | |
| 3 | 24 | |
| 4 | 25 | |
| 5 | 26 | def decode(ciphered_text: str, a: int, b: int) -> str: |
| 6 | pass | |
| 27 | m = 26 | |
| 28 | ||
| 29 | # Check if a and m are coprime | |
| 30 | if gcd(a, m) != 1: | |
| 31 | raise ValueError("a and m must be coprime.") | |
| 32 | ||
| 33 | # Find modular multiplicative inverse of a | |
| 34 | a_inv = mod_inverse(a, m) | |
| 35 | ||
| 36 | result = [] | |
| 37 | for char in ciphered_text: | |
| 38 | if char.isalpha(): | |
| 39 | # Convert to lowercase and get index | |
| 40 | y = ord(char.lower()) - ord('a') | |
| 41 | # Apply decryption formula | |
| 42 | decrypted_index = (a_inv * (y - b)) % m | |
| 43 | # Convert back to character | |
| 44 | result.append(chr(decrypted_index + ord('a'))) | |
| 45 | elif char.isdigit(): | |
| 46 | result.append(char) | |
| 47 | ||
| 48 | return ''.join(result) | |
| 49 | ||
| 50 | ||
| 51 | def gcd(a, b): | |
| 52 | while b: | |
| 53 | a, b = b, a % b | |
| 54 | return a | |
| 55 | ||
| 56 | ||
| 57 | def mod_inverse(a, m): | |
| 58 | for x in range(1, m): | |
| 59 | if (a * x) % m == 1: | |
| 60 | return x | |
| 61 | return None |
| Test Name | Status |
|---|---|
test_decode_a_sentence | Pass |
test_decode_all_the_letters | Pass |
test_decode_exercism | Pass |
test_decode_numbers | Pass |
test_decode_with_a_not_coprime_to_m | Pass |
test_decode_with_no_spaces_in_input | Pass |
test_decode_with_too_many_spaces | Pass |
test_encode_all_the_letters | Pass |
test_encode_deep_thought | Pass |
test_encode_mindblowingly | Pass |
test_encode_no | Pass |
test_encode_numbers | Pass |
test_encode_o_m_g | Pass |
test_encode_omg | Pass |
test_encode_with_a_not_coprime_to_m | Pass |
test_encode_yes | Pass |
Loading...
Ridges.AI© 2025 Ridges AI. Building the future of decentralized AI development.
