1

This https://www.codechef.com/CCRR2021/problems/CCRR002 is the codechef contest question. I can't figure out that what's wrong with my C++ code

#include<bits/stdc++.h>
using namespace std;

int main()
{
    int T;
    cin>>T;
    while(T--){
        int l;
        cin>>l;
        for(int i=pow(10,l-1);i<pow(10,l);i++)
        {
            if(i%10!=0)
                cout<<i<<endl;
        }
    }
    return 0;
}

Raashi was given a task to a crack password. Given a length ‘l′, Raashi wants to try all passwords of length ‘l′. Help her to find all possible passwords of length ‘l′ using recursion. Digits of the password are from 1 to 9.

Input: First line contains integer ‘t’, denoting number of testcases. For each testcase: There is one integer ‘l’. Output: For each testcase print all the possible passwords separated by new line.

Constraints 1≤t≤6 1≤l≤6

Sample Input: 1 2

Sample Output: 11 12 13 14 15 16 17 18 19 21 22 23 24 25 26 27 28 29 31 32 33 34 35 36 37 38 39 41 42 43 44 45 46 47 48 49 51 52 53 54 55 56 57 58 59 61 62 63 64 65 66 67 68 69 71 72 73 74 75 76 77 78 79 81 82 83 84 85 86 87 88 89 91 92 93 94 95 96 97 98 99

selbie
  • 100,020
  • 15
  • 103
  • 173
Anshul Sharma
  • 31
  • 1
  • 3

1 Answers1

2

pow is dangerous because it's heavily optimized to return an approximation as a floating point value. It might return 9999.9999999 on certain systems when your invoke pow(10,5), even though you expected it to return 10000.0. That issue is heavily discussed here: Why pow(10,5) = 9,999 in C++

Back to the original coding question. The question on that coding challenge site specifically calls for recursion. To make it happy and without using any math libraries:

#include <iostream>
#include <string>
using namespace std;

void enumerate(const string& prefix, int length)
{
    if (length <= 0)
    {
        cout << prefix << endl;
        return;
    }

    for (char c = '1'; c <= '9'; c++)
    {
        string s = prefix + c;
        enumerate(s, length - 1);
    }
}


int main()
{
    int testCaseCount, length;

    cin >> testCaseCount;
    for (int i = 0; i < testCaseCount; i++)
    {
        cin >> length;
        enumerate("", length);
    }
    return 0;
}
selbie
  • 100,020
  • 15
  • 103
  • 173