aboutsummaryrefslogtreecommitdiff
path: root/challenge-102/paulo-custodio/cpp/ch-1.cpp
blob: 01d88ccd5a7dda429401f5fac0c62eca808d108d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/*
Challenge 102

TASK #1 � Rare Numbers
Submitted by: Mohammad S Anwar

You are given a positive integer $N.

Write a script to generate all Rare numbers of size $N if exists. Please
checkout the page for more information about it.
Examples

(a) 2 digits: 65
(b) 6 digits: 621770
(c) 9 digits: 281089082
*/

#include <iostream>
#include <cmath>

int ipow(int base, int exp) {
    int result = 1;
    for (;;) {
        if (exp & 1)
            result *= base;
        exp >>= 1;
        if (!exp)
            break;
        base *= base;
    }
    return result;
}

int invert_number(int r) {
    int r1 = 0;
    while (r != 0) {
        r1 = r1 * 10 + (r % 10);
        r = r / 10;
    }
    return r1;
}

bool is_perfect_square(int n) {
    double s = sqrt((double)n);
    if (floor(s) == s)
        return true;
    else
        return false;
}

void print_rare(int n) {
    int start = ipow(10, n - 1);
    int end = ipow(10, n );
    for (int r = start; r < end; r++) {
        int r1 = invert_number(r);
        if (is_perfect_square(r + r1) && r >= r1 && is_perfect_square(r - r1))
            std::cout << r << std::endl;
    }
}

int main(int argc, char* argv[]) {
    if (argc != 2) {
        std::cerr << "Usage: ch-1 N" << std::endl;
        return EXIT_FAILURE;
    }
    else
        print_rare(atoi(argv[1]));
}