
#include <bits/stdc++.h>
using namespace std;

// Check Prime Number
bool isPrime(long long n) {
    if(n <= 1) {
        return false;
    }

    for(long long i = 2; i * i <= n; i++) {
        if(n % i == 0) {
            return false;
        }
    }

    return true;
}

// Modular Exponentiation
long long modPow(long long base, long long exp, long long mod) {
    base %= mod;
    long long ans = 1;

    while(exp >= 1) {
        if(exp % 2 == 1) {
            ans = (ans * base) % mod;
        }

        base = (base * base) % mod;
        exp /= 2;
    }

    return ans;
}

// Check Primitive Root
bool isPrimitiveRoot(long long g, long long p) {
    set<long long> values;

    for(long long i = 1; i < p; i++) {
        values.insert(modPow(g, i, p));
    }

    return values.size() == p - 1;
}

int main() {
    long long p, g, a, b;

    cout << "Enter prime number (p): ";
    cin >> p;

    if(!isPrime(p)) {
        cout << "p is not a prime number!";
        return 0;
    }

    cout << "Enter primitive root (g): ";
    cin >> g;

    if(g <= 0 || g >= p || !isPrimitiveRoot(g, p)) {
        cout << "Invalid primitive root!";
        return 0;
    }

    // Private Keys
    cout << "Enter Alice's private key: ";
    cin >> a;

    cout << "Enter Bob's private key: ";
    cin >> b;

    if(a <= 0 || b <= 0) {
        cout << "Private keys must be positive!";
        return 0;
    }

    // Generate Public Keys
    long long A = modPow(g, a, p);
    long long B = modPow(g, b, p);

    cout << "\nAlice's Public Key = " << A << endl;
    cout << "Bob's Public Key = " << B << endl;

    // Generate Shared Secret Keys
    long long keyAlice = modPow(B, a, p);
    long long keyBob = modPow(A, b, p);

    cout << "\nAlice's Shared Key = " << keyAlice << endl;
    cout << "Bob's Shared Key = " << keyBob << endl;

    if(keyAlice == keyBob) {
        cout << "\nShared Secret Key = " << keyAlice << endl;
        cout << "Key Exchange Successful!";
    }
    else {
        cout << "Key Exchange Failed!";
    }

    return 0;
}
