# Help with simple decryption program plz!

• 03-10-2010
allen9190
Help with simple decryption program plz!
Hi, I'm working on an assignment that says write a program that encrypts a 4-digit integer and and another program that decrypts it.
I'm having trouble writing the decrypt program because I don't know how to reverse the modulus operation.

To encrypt the 4-digit integer, replace each digit with the result of adding 7 to the digit and getting the remainder after dividing the new value by 10. Then swap the first digit with the third, and swap the second digit with the fourth. Then print the encrypted integer.

Here is the code to my encryption program. Thanks in advance!

Code:

```#include <iostream> using namespace std; int main() {         int num;         int d1, d2, d3, d4; //digits 1-4         int r1, r2, r3, r4; //remainders 1-4         int n1, n2, n3, n4; //digits 1-4 of encrypted number                 cout << "Enter a 4-digit integer to encrypt: ";         cin >> num;         //separate each digit         d1 = num / 1000;         r1 = num % 1000;         d2 = r1 / 100;         r2 = r1 % 100;         d3 = r2 / 10;         r3 = r2 % 10;         d4 = r3 / 1;         r4 = r3 % 1;         //encrypt each digit         n1 = (d1 + 7) % 10;         n2 = (d2 + 7) % 10;         n3 = (d3 + 7 )% 10;         n4 = (d4 + 7) % 10;         //swap 1st digit with 3rd and 2nd with 4th         //Output new encrypted number         cout << "Encrypted number is: " << n3 << n4 << n1 << n2; }```
• 03-10-2010
Aisthesis
hmmm... well, undoing the swaps is easy.

then you have to decrypt the result of (d + 7) % 10 so... if n is 0 thru 6, then d was 3 thru 9. and if n is 7 thru 9, d was 0 thru 2. doesn't that mean d = (n + 3) % 10?

i think that gets you there: just undo the swaps, then calculate the digit based on the above formula.
• 03-10-2010
allen9190
Thanks alot! I'm not that great with the modulus operator, so it wasn't apparent to me how to reverse the effects. So for a general formula, do u just subtract/add the number you originally applied from the mod number. Like the original was ( d + 7 ) % 10. Do I just do 10 - 7 = 3. Then the reverse equation is (d + 3) % 10 ?
• 03-11-2010
Aisthesis
basically, yes.

the mathematical explanation is that the modulus operator defines an additive group.

a more intuitive version: think of it as the numbers on the dial of a kind of custom clock, and just for fun, let's not put 10 numbers on there but 16 (i.e., hex). if you start with a "time" d and add h hours (h < 16), then you can get back to d by subracting h hours. And that amounts to moving forward by 16 - h.