#include<bits/stdc++.h>
#define REP(i,n) for (int i = 1; i <= n; i++)
#define mod 1000000007
#define pb push_back
#define ff first
#define ss second
#define ii pair<int,int>
#define vi vector<int>
#define vii vector<ii>
#define lli long long int
#define endl '\n'

using namespace std;
int b;
int fact[10];

void initFactorial()
{
	fact[0] = 1;
	for(int i=1;i<10;i++)
	fact[i] = fact[i-1] * i;
}

bool isFactorian(int N)
{
	int value = 0;
	int temp = N;
	
	while(temp)
	{
		int current_digit = temp % b;
		temp /= b;
		
		value += fact[current_digit];
	}
	
	return value == N;
}

int getBiggestFactorian(int N)
{
	for(int i=N-1;i>=1;i--)
	if(isFactorian(i)) return i;
	
	return -1;
}

int main()
{
	initFactorial();
	cin>>b;
	cout<<getBiggestFactorian(1500000);
}




/*

it is more of an implementation problem , the toughest part of it will be to convert a given number in base 10 to base b (so you can understand this is not that difficult problem).

so here is how we can solve this problem.

1. pre calculate factorials from 0 to 9 (because we only need factorial of digits).

2. run a loop from 1500000 - 1 to 0 and check whether the current number is factorian number or not.

3. if the current number is factorian number stop the loop and print current number.

step 2 requires to check whether the given number is factorian number or not , for that you need to convert the current number from base 10 to base b after that you can easily check that.

I am providing the code , you can check the implementation details there.

*/