/*=====================================
*
* AUTHOR : maxkibble
* CREATED: 2019.09.08 15:39:59
* PROBELM: UVALive 3722
*
=====================================*/
#include <bits/stdc++.h>
using namespace std;
#define fi first
#define se second
#define pb push_back
typedef long long ll;
typedef pair<int, int> pii;
ll mypow(ll a, ll n, ll c) {
ll ans = 1;
while (n) {
if (n & 1) ans = ans * a % c;
a = a * a % c;
n >>= 1;
}
return ans;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
ll x, a, n, c;
while (cin >> x >> a >> n >> c) {
if (x == 0) break;
ll an = mypow(a, n, c);
ll A = an * x % c;
ll B = ((an - 1) % c + c) % c * a % c;
ll C = mypow(a - 1, c - 2, c);
ll ans;
if ((a - 1) % c == 0) {
assert(A == x % c);
ans = A - n % c;
}
else ans = A - B * C;
ans = (ans % c + c) % c;
cout << ans << "\n";
}
return 0;
}
Lyo9PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09CiogICAKKiAgIEFVVEhPUiA6IG1heGtpYmJsZQoqICAgQ1JFQVRFRDogMjAxOS4wOS4wOCAxNTozOTo1OQoqICAgUFJPQkVMTTogVVZBTGl2ZSAzNzIyCioKPT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PSovCgoKI2luY2x1ZGUgPGJpdHMvc3RkYysrLmg+Cgp1c2luZyBuYW1lc3BhY2Ugc3RkOwoKI2RlZmluZSBmaSBmaXJzdAojZGVmaW5lIHNlIHNlY29uZAojZGVmaW5lIHBiIHB1c2hfYmFjawoKdHlwZWRlZiBsb25nIGxvbmcgbGw7CnR5cGVkZWYgcGFpcjxpbnQsIGludD4gcGlpOwoKbGwgbXlwb3cobGwgYSwgbGwgbiwgbGwgYykgewogIGxsIGFucyA9IDE7CiAgd2hpbGUgKG4pIHsKICAgIGlmIChuICYgMSkgYW5zID0gYW5zICogYSAlIGM7CiAgICBhID0gYSAqIGEgJSBjOwogICAgbiA+Pj0gMTsKICB9CiAgcmV0dXJuIGFuczsKfQoKaW50I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