Generating the largest decent number of given number of digits
Since you're asking where the code is failing:

Your logic is flawed for at least the case n % 5 == 0 in which case you assume the whole number must always be made of 3's but that is wrong since for example for n = 15 the number consisting of all 5's would be larger and still fulfill the requirements.

Also your code invokes undefined behaviour since flag might be used before it is initialized in the case n % 5 == 0.

Ultimately what you are looking for is a solution to:

3 * f + 5 * t = n


where f is the number of 5's and t is the number of 3's and n is the known length.

One simple way to solve this is to transform it into:

f = n/3 - 5/3 * t


Now all you need to do is to check if there is a solution for t with 0 &lt;= t &lt;= n where f is a whole number which ultimately boils down to finding the smallest t where

n % 3 == (5 * t) % 3


So you have the three cases. Together with the knowledge that 5 % 3 == 2 we can deduce:


n % 3 == 0: (5 * t) % 3 == 0 for t = 0, 3, 6, 9, 12, 15, 18
n % 3 == 1: (5 * t) % 3 == 1 for t = 2, 5, 8, 11, 14, 17, 20
n % 3 == 2: (5 * t) % 3 == 1 for t = 1, 4, 7, 10, 13, 16, 19


Since we're interested in the smallest t (so the resulting number has the maximum number of 5's and is therefor the largest matching one) this leaves you with roughly this pseudo-code algorithm

switch (n % 3):
    case 0: t = 0;
    case 1: t = 2;
    case 2: t = 1;

if (5 * t &lt;= n):
    print "5".repeat(n - 5 * t) + "3".repeat(5 * t) 
else
    print "-1"