I've been trying for a while to get this right but I guess I can't do the math.
I'm using this line to encrypt each character for the Vigenères Cypher:
int letter = ((p(i) - 96) + (k[j] - 97) % 26 + 96;
This works well for most letters, but when the encrypted result should be a z
(122), I keep getting a '
(96). I understand how this happens, since when the addition inside the parenthesis is a multiple of 26, I get 26 % 26 = 0 -> 0 + 96 = 96 = '
. However, I really don't know how to get around it!
Some more info: I have four 'if' conditions, or rather two 'if' each containing two more:
- First, test if the character in the unencrypted text is lowercase or uppercase.
- Then, inside each option, test if the character in the key is lowercase or uppercase
So this looks a bit like this:
if (isupper(p[i]))
{
if (isupper(k[j]))
{
...
}
else if (islower(k[j]))
{
...
}
}
else if (islower(p[i]))
{
if (isupper(k[j]))
{
...
}
else if (islower(k[j]))
{
...
}
This way, the check50 works fine and I get all the smileys. However, when I run other tests, I get some bugs. For example:
jharvard@appliance (~/Dropbox/pset2): ./vigenere bacon
Meet me at the park at eleven am
Negh 'f av huf pcfx bt g'rwep o'
Instead of:
Negh zf av huf pcfx bt gzrwep oz
I'm tempted to give up since check50 works fine, but this has been obsessing me for a couple days so I'd still like to correct it.