Task 1: Strong and Weak Primes
Write a script to generate first 10 strong and weak prime numbers.
A prime number $p_n$ is:
- Strong if $p_n > (p_{n-1} + p_{n+1}) / 2$
- Weak if $p_n < (p_{n-1} + p_{n+1}) / 2$
Output
Strong primes: 11,17,29,37,53,59,67,79,97,101
Weak primes: 3,7,13,19,23,31,43,47,61,73
Logic
Generate prime numbers sequentially. For each prime $p_n$, look at the previous prime $p_{n-1}$ and the next prime $p_{n+1}$ to evaluate whether the current prime is greater or less than the arithmetic mean of its neighbors. We collect the first 10 of each type.
Perl Solution
ch-1.pl
my @strong_primes;
my @weak_primes;
my $last_prime = 2;
my $current_prime;
my $next_prime;
sub is_prime {
my $candidate = shift;
for my $n ( 2 .. int( sqrt($candidate) ) ) {
return 0 if ( $candidate % $n == 0 );
}
return 1;
}
my $n = 2;
while (1) {
$n++;
next unless is_prime($n);
unless ($current_prime) {
$current_prime = $n;
next;
}
$next_prime = $n;
push @strong_primes, $current_prime if $current_prime > ($last_prime + $next_prime)/2 and scalar @strong_primes < 10;
push @weak_primes, $current_prime if $current_prime < ($last_prime + $next_prime)/2 and scalar @weak_primes < 10;
$last_prime = $current_prime;
$current_prime = $n;
last if (scalar @strong_primes > 9) and (scalar @weak_primes > 9);
}
Python Solution
ch-1.py
def is_prime(n: int) -> bool:
if n < 2: return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0: return False
return True
# Strong/Weak Prime logic checks:
# p > (prev_prime + next_prime) / 2 -> Strong
# p < (prev_prime + next_prime) / 2 -> Weak
Task 2: Vigenère Cipher
Write a script to implement the Vigenère cipher. The script should be able to encode and decode messages based on a keyword.
Example
Plaintext: ATTACKATDAWN, Key: LEMON -> Ciphertext: LXFOPVEFRNHR
Logic
The Vigenère cipher shifts letters of a plaintext message based on the corresponding letters of a repeated key. The shift amount for letter $K$ is $ord(K) - ord('A')$. For encryption, we add the shift modulo 26; for decryption, we subtract the shift modulo 26.
Perl Solution
ch-2.pl
sub encode_letter {
my ($plain, $key) = @_;
my $shift_plain = ord($plain) - ord('A');
my $shift_key = ord($key) - ord('A');
return chr(ord('A') + ($shift_plain + $shift_key) % 26);
}
sub decode_letter {
my ($key, $cypher) = @_;
my $shift_key = ord($key) - ord('A');
my $shift_cypher = ord($cypher) - ord('A');
return chr(ord('A') + ($shift_cypher - $shift_key) % 26);
}
Python Solution
ch-2.py
def vigenere_encipher(plaintext: str, key: str) -> str:
key = "".join(c.upper() for c in key if c.isalpha())
alpha_chars = [c for c in plaintext if c.isalpha()]
result = []
for idx, char in enumerate(alpha_chars):
shift = ord(key[idx % len(key)].upper()) - ord("A")
is_upper = char.isupper()
base = ord("A") if is_upper else ord("a")
shifted = (ord(char) - base + shift) % 26 + base
result.append(chr(shifted))
return "".join(result)