n, p = map(int,input().split()) MOD = 10**9+7 a = [0, 1] for i in range(n-2): a.append((a[i+1]*p+a[i])%MOD) s = sum(i**2 for i in a) ans = (pow(sum(a), 2, MOD)+s)*pow(2, MOD-2, MOD) ans %= MOD print(ans)