#import <Foundation/Foundation.h>
#import <stdlib.h>
#import <stdarg.h>
typedef NSInteger Int;
#ifndef _OS_OSTYPES_H
typedef NSUInteger UInt;
#endif
/// NSSet literal
#if !defined($)
#define $(...)  ([NSSet setWithArray: @[__VA_ARGS__]])
#endif
@interface NSString (Extension)
-(NSMutableArray*)componentsSeparatedByCharacter:(unichar)separator;
-(NSMutableArray*)numbersSeparatedByString:(NSString*)separator;
-(NSMutableArray*)numbersSeparatedByCharacter:(unichar)separator;
-(NSMutableArray*)splitCharacterEvery:(UInt)number;
-(NSMutableArray*)characterStrings; // 1文字ずつの NSString* の配列を返す
-(NSMutableArray*)characters; // 1文字ずつの unichar をラップした NSNumber の配列を返す
-(unichar)firstCharacter;
-(unichar)lastCharacter;
-(NSString*)leadingSubstringWithLength:(UInt)length;
-(NSString*)trailingSubstringWithLength:(UInt)length;
@end
@interface NSArray (Extension)
+(instancetype)arrayWithRange:(NSRange)range;
-(Int)integerAtIndex:(UInt)index;
-(Int)firstInteger;
-(Int)secondInteger;
-(Int)thirdInteger;
-(Int)fourthInteger;
-(double)doubleAtIndex:(UInt)index;
-(NSString*)stringAtIndex:(UInt)index;
-(NSMutableArray*)sortedArrayWithAscending:(BOOL)ascending; // NSNumber* を要素に持つ配列をソート
-(NSMutableArray*)quickSortedArrayWithAscending:(BOOL)ascending; // Int をラップした NSNumber* を要素に持つ配列をクイックソート
-(Int)gcd;
// MARK: Key-Value Coding
-(NSMutableArray*)unique;
-(Int)maxInteger;
-(Int)minInteger;
-(Int)sumInteger;
-(double)maxDouble;
-(double)minDouble;
-(double)sumDouble;
-(double)average;
#ifndef _OS_OSTYPES_H
-(id)firstObject;
#endif
@end
/// MARK: - 定数の定義
#ifndef M_PI
#define M_E         2.71828182845904523536028747135266250   /* e              */
#define M_LOG2E     1.44269504088896340735992468100189214   /* log2(e)        */
#define M_LOG10E    0.434294481903251827651128918916605082  /* log10(e)       */
#define M_LN2       0.693147180559945309417232121458176568  /* loge(2)        */
#define M_LN10      2.30258509299404568401799145468436421   /* loge(10)       */
#define M_PI        3.14159265358979323846264338327950288   /* pi             */
#define M_PI_2      1.57079632679489661923132169163975144   /* pi/2           */
#define M_PI_4      0.785398163397448309615660845819875721  /* pi/4           */
#define M_1_PI      0.318309886183790671537767526745028724  /* 1/pi           */
#define M_2_PI      0.636619772367581343075535053490057448  /* 2/pi           */
#define M_2_SQRTPI  1.12837916709551257389615890312154517   /* 2/sqrt(pi)     */
#define M_SQRT2     1.41421356237309504880168872420969808   /* sqrt(2)        */
#define M_SQRT1_2   0.707106781186547524400844362104849039  /* 1/sqrt(2)      */
#endif
/// MARK: - 整数の演算
Int iminvar(Int len, ...); // 整数可変長のmin。第1引数は比較するものの数。
Int imin2(Int a, Int b);
Int imin3(Int a, Int b, Int c);
Int imaxvar(Int len, ...); // 整数可変長のmax。第1引数は比較するものの数。
Int imax2(Int a, Int b);
Int imas3(Int a, Int b, Int c);
Int ipow(Int x, Int n); // x^n (xとnは非負整数)
Int gcd(Int a, Int b); // GCD
Int gcd2(Int a, Int b); // メモ化GCD
/// MARK: - doubleの演算
double fabs(double x);
double sqrt(double x);
double sin(double x);
double cos(double x);
double tan(double x);
double sinDeg(double x);
double cosDeg(double x);
double tanDeg(double x);
double fceil(double num);
double ffloor(double num);
@interface NSNumber (Extension)
-(NSString*)stringWithBase:(UInt)base; //n進法表記文字列を返す（基数：base）
-(NSString*)stringWithBase:(UInt)base zeroPadding:(UInt)padding; //n進法表記文字列を返す（基数：base，0-paddingする桁数：padding）
@end
@interface StdIO : NSObject
+(NSMutableString*)stringFromStdIn;
+(NSMutableArray*)stringsFromStdInSeparatedByString:(NSString*)separator;
+(NSMutableArray*)stringsFromStdInSeparatedByCharacter:(unichar)separator;
+(NSMutableArray*)numbersFromStdInSeparatedByString:(NSString*)separator;
+(NSMutableArray*)numbersFromStdInSeparatedByCharacter:(unichar)separator;
+(void)put:(char*)format, ...;
+(void)puts:(NSString*)format, ...;
@end
@interface NSMutableString (Extension)
-(NSMutableString*)unshift:(NSString*)string;
-(NSString*)shiftWithLength:(UInt)length;
-(NSMutableString*)push:(NSString*)string;
-(NSString*)popWithLength:(UInt)length;
@end
@implementation NSString (Extension)
-(NSMutableArray*)componentsSeparatedByCharacter:(unichar)separator
{
    return [NSMutableArray arrayWithArray: [self componentsSeparatedByString:[NSString stringWithFormat:@"%c", separator]]];
}
-(NSMutableArray*)numbersSeparatedByString:(NSString*)separator
{
    NSArray *strings = [self componentsSeparatedByString: separator];
    NSMutableArray *numbers = [NSMutableArray array];
    for (NSString *string in strings) {
        if (![string isEqualToString:@""]) {
            [numbers addObject: [NSNumber numberWithInteger: [string integerValue]]];
        }
    }
    return numbers;
}
-(NSMutableArray*)numbersSeparatedByCharacter:(unichar)separator
{
    return [self numbersSeparatedByString:[NSString stringWithFormat:@"%c", separator]];
}
-(NSMutableArray*)splitCharacterEvery:(UInt)number
{
    if ([self length] <= number) {
        return [NSMutableArray arrayWithObject: self];
    }
    NSMutableArray  *mArray = [NSMutableArray array];
    NSMutableString *mStr   = [NSMutableString stringWithString: self];
    NSRange range = NSMakeRange(0, number);
    while ([mStr length] > 0) {
        if ([mStr length] < number) {
            [mArray addObject: [NSString stringWithString: mStr]];
            [mStr deleteCharactersInRange:NSMakeRange(0, [mStr length])];
        } else {
            [mArray addObject: [mStr substringWithRange: range]];
            [mStr deleteCharactersInRange: range];
        }
    }
    return mArray;
}
-(NSMutableArray*)characterStrings {
    return [self splitCharacterEvery: 1];
}
-(NSMutableArray*)characters {
    NSMutableArray *result = [NSMutableArray array];
    for (UInt i=0; i<[self length]; i++) {
        [result addObject: @([self characterAtIndex: i])];
    }
    return result;
}
-(unichar)firstCharacter
{
    return [self characterAtIndex: 0];
}
-(unichar)lastCharacter
{
    return [self characterAtIndex: [self length] - 1];
}
-(NSString*)leadingSubstringWithLength:(UInt)length
{
    if (length <= [self length]) {
        return [self substringWithRange: NSMakeRange(0, length)];
    } else {
        return nil;
    }
}
-(NSString*)trailingSubstringWithLength:(UInt)length
{
    UInt mylength = [self length];
    if (length <= mylength) {
        return [self substringWithRange: NSMakeRange(mylength - length, length)];
    } else {
        return nil;
    }
}
@end
/// MARK: - 整数の演算
Int iminvar(Int len, ...) {
    Int _min, num;
    va_list ap;
    va_start(ap, len);
    _min = va_arg(ap, Int);
    for (Int i = 1; i < len; i++) {
        num = va_arg(ap, Int);
        if (num < _min)
            _min = num;
    }
    va_end(ap);
    return _min;
}
Int imin2(Int a, Int b) {
    return iminvar(2, a, b);
}
Int imin3(Int a, Int b, Int c) {
    return iminvar(3, a, b, c);
}
Int imaxvar(Int len, ...) {
    Int _max, num;
    va_list ap;
    va_start(ap, len);
    _max = va_arg(ap, Int);
    for (Int i = 1; i < len; i++) {
        num = va_arg(ap, Int);
        if (num > _max)
            _max = num;
    }
    va_end(ap);
    return _max;
}
Int imax2(Int a, Int b) {
    return imaxvar(2, a, b);
}
Int imax3(Int a, Int b) {
    return imaxvar(3, a, b);
}
Int ipow(Int x, Int n) {
    int result = 1;
    while (n > 0) {
        if ((n % 2) == 0) {
            x *= x;
            n >>= 1;
        } else {
            result *= x;
            n--;
        }
    }
    return result;
}
Int gcd(Int a, Int b){
    Int M = MAX(a, b);
    Int m = MIN(a, b);
    if (m == 0) {
        return M;
    }
    Int r = M % m;
    return (r==0) ? m : gcd(r, m);
}
NSMutableDictionary *gcdmap;
Int gcd2(Int a, Int b) {
    if (!gcdmap) {
        gcdmap = [NSMutableDictionary dictionary];
    }
    Int M = MAX(a, b);
    Int m = MIN(a, b);
    if (m == 0) {
        return M;
    }
    NSString *key = [NSString stringWithFormat:@"%ld,%ld", M, m];
    NSNumber *gcd = (NSNumber*)[gcdmap objectForKey:key];
    if (gcd) {
        return [gcd integerValue];
    } else {
        Int r = M % m;
        if (r == 0) {
            [gcdmap setObject:@(m) forKey:key];
            return m;
        } else {
            Int result = gcd2(m, r);
            [gcdmap setObject:@(result) forKey:key];
            return result;
        }
    }
}
/// MARK: - doubleの演算
double fabs(double x) {
    return (x>=0) ? x : -x;
}
double sqrt(double x) {
    double         xHalf = 0.5 * x;
    long long int  tmp   = 0x5FE6EB50C7B537AAl - ( *(long long int*)&x >> 1);//initial guess
    double         xRes  = * (double*)&tmp;
    xRes *= ( 1.5 - ( xHalf * xRes * xRes ) );
    xRes *= ( 1.5 - ( xHalf * xRes * xRes ) );
    xRes *= ( 1.5 - ( xHalf * xRes * xRes ) );
    xRes *= ( 1.5 - ( xHalf * xRes * xRes ) );
    return xRes * x;
}
double sin(double x) {
    int i = 1;
    double cur = x;
    double acc = 1;
    double fact= 1;
    double pow = x;
    while (fabs(acc) > .00000001 && i < 100){
        fact *= ((2*i)*(2*i+1));
        pow *= -1 * x*x;
        acc =  pow / fact;
        cur += acc;
        i++;
    }
    return cur;
}
double cos(double x) {
    return sin(M_PI_2 - x);
}
double tan(double x) {
    return sin(x)/cos(x);
}
double sinDeg(double x) {
    return sin(x * M_PI/180);
}
double cosDeg(double x) {
    return cos(x * M_PI/180);
}
double tanDeg(double x) {
    return tan(x * M_PI/180);
}
double fceil(double num) {
    long inum = (long)num;
    return inum + (((num != inum) && (num > 0)) ? 1 : 0);
}
double ffloor(double num) {
    long inum = (long)num;
    return inum + (((num != inum) && (num < 0)) ? -1 : 0);
}
@implementation NSArray (Extension)
+(instancetype)arrayWithRange:(NSRange)range
{
    NSMutableArray *result = [NSMutableArray array];
    for(UInt loc = range.location; loc< range.location + range.length; loc++) {
        [result addObject: @(loc)];
    }
    return result;
}
-(Int)integerAtIndex:(UInt)index
{
    return [[self objectAtIndex:index] integerValue];
}
-(Int)firstInteger
{
    return [self integerAtIndex: 0];
}
-(Int)secondInteger
{
    return [self integerAtIndex: 1];
}
-(Int)thirdInteger
{
    return [self integerAtIndex: 2];
}
-(Int)fourthInteger
{
    return [self integerAtIndex: 3];
}
-(double)doubleAtIndex:(UInt)index
{
    return [[self objectAtIndex:index] doubleValue];
}
-(NSString*)stringAtIndex:(UInt)index
{
    return (NSString*)[self objectAtIndex:index];
}
-(NSMutableArray*)sortedArrayWithAscending:(BOOL)ascending
{
    NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey: @"self" ascending: ascending];
    NSArray *sortedArray = [self sortedArrayUsingDescriptors: @[descriptor]];
    return [NSMutableArray arrayWithArray: sortedArray];
}
-(NSMutableArray*)quickSortedArrayWithAscending:(BOOL)ascending
{
    // Time complexity: O(n^2).
    //  * First time arround is to separate the entire array.
    //  * Second time around should sort the rest of the array.
    // Space complexity: O(log n)  +1 for unsortedArray but the mutable copy never gets added to the autorelease pool.
    // All of the arrays that are not attached to the returnArray are released by a compiler pass at the end of the method.
    UInt count = [self count];
    if (count <= 1) {
        return [NSMutableArray arrayWithArray: self];
    }
    Int pivot = [[self objectAtIndex: (count/2)] integerValue];
    NSMutableArray *smallerThanArray = [NSMutableArray array];
    NSMutableArray *largerThanArray = [NSMutableArray array];
    NSMutableArray *pivotArray = [NSMutableArray array];
    [pivotArray addObject: @(pivot)];
    for (Int e = 0; e < count; e++) {
        Int num = [[self objectAtIndex:e] integerValue];
        if (num < pivot) {
            [smallerThanArray addObject: @(num)];
        } else if (num > pivot) {
            [largerThanArray addObject: @(num)];
            // To address the possibly duplicate that is defined in the pivot, in this case 4.
        } else if (e != (count/2) && pivot == num) {
            [pivotArray addObject: @(num)];
        }
    }
    NSMutableArray *returnArray = [NSMutableArray array];
    if (ascending) {
        [returnArray addObjectsFromArray: [smallerThanArray quickSortedArrayWithAscending: ascending]];
        [returnArray addObjectsFromArray: pivotArray];
        [returnArray addObjectsFromArray: [largerThanArray quickSortedArrayWithAscending: ascending]];
    } else {
        [returnArray addObjectsFromArray: [largerThanArray quickSortedArrayWithAscending: ascending]];
        [returnArray addObjectsFromArray: pivotArray];
        [returnArray addObjectsFromArray: [smallerThanArray quickSortedArrayWithAscending: ascending]];
    }
    return returnArray;
}
-(Int)gcd
{
    UInt count = [self count];
    switch (count) {
        case 0:
            return 0;
        case 1:
            return [[self objectAtIndex:0] integerValue];
        case 2:
        {
            Int a = [[self objectAtIndex:0] integerValue];
            Int b = [[self objectAtIndex:1] integerValue];
            return gcd(a,b);
        }
        default:
        {
            UInt c = [self count];
            NSRange range1 = NSMakeRange(0, c/2);
            NSRange range2 = NSMakeRange(c/2, count - c/2);
            NSArray *a = [self subarrayWithRange: range1];
            NSArray *b = [self subarrayWithRange: range2];
            return gcd([a gcd], [b gcd]);
        }
    }
}
/// MARK:- Key-Value Coding
-(NSMutableArray*)unique
{
    return [NSMutableArray arrayWithArray:[self valueForKeyPath:@"@distinctUnionOfObjects.self"]];
}
-(Int)maxInteger
{
    return [[self valueForKeyPath:@"@max.self"] integerValue];
}
-(Int)minInteger
{
    return [[self valueForKeyPath:@"@min.self"] integerValue];
}
-(Int)sumInteger
{
    return [[self valueForKeyPath:@"@sum.self"] integerValue];
}
-(double)maxDouble;
{
    return [[self valueForKeyPath:@"@max.self"] doubleValue];
}
-(double)minDouble;
{
    return [[self valueForKeyPath:@"@min.self"] doubleValue];
}
-(double)sumDouble;
{
    return [[self valueForKeyPath:@"@sum.self"] doubleValue];
}
-(double)average;
{
    return [[self valueForKeyPath:@"@avg.self"] doubleValue];
}
#ifndef _OS_OSTYPES_H
-(id)firstObject
{
    if ([self count] > 0) {
        return [self objectAtIndex: 0];
    } else {
        return nil;
    }
}
#endif
@end
@implementation NSNumber (Extension)
-(NSString*)stringWithBase:(UInt)base
{
    NSInteger value = [self integerValue];
    Int r = value % base;
    Int q = value / base;
    unichar s = (r<10) ? ('0'+r) : ('A'+(r-10));
    if (q==0) {
        return [NSString stringWithFormat:@"%c", s];
    } else {
        return [NSString stringWithFormat:@"%@%c", [@(q) stringWithBase: base], s];
    }
}
-(NSString*)stringWithBase:(UInt)base zeroPadding:(UInt)padding
{
    NSString *result = [self stringWithBase: base];
    UInt n = [result length];
    NSMutableString *Result = [NSMutableString string];
    for(Int i=n+1; i<=padding; i++) {
        [Result appendString: @"0"];
    }
    [Result appendString: result];
    return Result;
}
@end
@implementation NSMutableString (Extension)
-(NSMutableString*)unshift:(NSString*)string
{
    [self insertString: string atIndex: 0];
    return self;
}
-(NSString*)shiftWithLength:(UInt)length
{
    if ([self length] >= length) {
        NSRange range = NSMakeRange(0, length);
        NSString *first = [self substringWithRange: range];
        [self deleteCharactersInRange: range];
        return first;
    } else {
        return nil;
    }
}
-(NSString*)push:(NSString*)string
{
    [self appendString: string];
    return self;
}
-(NSString*)popWithLength:(UInt)length
{
    UInt mylength = [self length];
    if (length <= mylength) {
        NSRange range = NSMakeRange(mylength - length, length);
        NSString *last = [self substringWithRange: range];
        [self deleteCharactersInRange: range];
        return last;
    } else {
        return nil;
    }
}
@end
@implementation StdIO
+(NSMutableString*)stringFromStdIn
{
    NSFileHandle *handle = [NSFileHandle fileHandleWithStandardInput];
    NSMutableString *result = [NSMutableString string];
    NSData *data = [handle availableData];
    while ([data length] > 0) {
        [result appendString:[[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]];
        data = [handle availableData];
    }
    if ([result lastCharacter] == '\n') {
        [result popWithLength: 1];
    }
    return result;
}
+(NSMutableArray*)stringsFromStdInSeparatedByString:(NSString*)separator
{
    return [NSMutableArray arrayWithArray: [[StdIO stringFromStdIn] componentsSeparatedByString: separator]];
}
+(NSMutableArray*)stringsFromStdInSeparatedByCharacter:(unichar)separator
{
    return [NSMutableArray arrayWithArray: [[StdIO stringFromStdIn] componentsSeparatedByCharacter: separator]];
}
+(NSMutableArray*)numbersFromStdInSeparatedByString:(NSString*)separator
{
    return [[StdIO stringFromStdIn] numbersSeparatedByString: separator];
}
+(NSMutableArray*)numbersFromStdInSeparatedByCharacter:(unichar)separator
{
    return [[StdIO stringFromStdIn] numbersSeparatedByCharacter: separator];
}
+(void)putsToStdOut:(NSString*)string
{
    NSFileHandle *fileHandle = [NSFileHandle fileHandleWithStandardOutput];
    [fileHandle writeData:[string dataUsingEncoding: NSUTF8StringEncoding]];
    [fileHandle writeData:[@"\n" dataUsingEncoding: NSUTF8StringEncoding]];
}
+(void)put:(char*)format, ...
{
    va_list arguments;
    va_start(arguments, format);
    NSString *string = [[NSString alloc] initWithFormat: [NSString stringWithUTF8String: format] arguments: arguments];
    [StdIO putsToStdOut: string];
    va_end(arguments);
}
+(void)puts:(NSString*)format, ...
{
    va_list arguments;
    va_start(arguments, format);
    NSString *string = [[NSString alloc] initWithFormat: format arguments: arguments];
    [StdIO putsToStdOut: string];
    va_end(arguments);
}
@end
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSString *N = [StdIO stringFromStdIn];
        Int n= [N length];
        if (n<=2) {
            [StdIO put:"0"];
            return 0;
        }
        Int c = 27*(ipow(3,n-3)-1)/2 - 24*(ipow(2,n-3)-1) + 3*(n-3);
        //[StdIO put:"LESS = %ld", c];
        for(Int i=0;i<ipow(3,n);i++) {
            NSString *sss = [@(i) stringWithBase:3 zeroPadding:n];
            //[StdIO put:"checking %@", sss];
            NSArray *tri = [sss characters];
            if ([[tri unique] count] != 3) {
                continue;
            }
            //[StdIO put:"checking2 %@", [tri description]];
            NSMutableString *s = [NSMutableString string];
            for (NSNumber *t in tri) {
                unichar tc = [t unsignedIntegerValue];
                [s appendString: (tc == '0') ? @"3" : (tc == '1') ? @"5" : @"7"];
            }
            if ([s integerValue] <= [N integerValue]) {
                //[StdIO put:"FOUND=%@", s];
                c++;
            }
        }
        [StdIO put:"%ld", c];
    }
    return 0;
}


Measured memory_bytes: 93668