Check if the number can be represented as a power of integers

In the second task of this week’s Challenge, you have to find two integers that being powered as xy, give the requested integer number n.

In the second task of this week’s Challenge, you have to find two integers that being powered as xy, give the requested integer number n.

1

Let me again solve a bit different task first, and just tell if such pair exists.

my $n = 9;

say $n ∈ [X**] ((1..$n.sqrt) xx 2);

This program prints either True (e.g., for the input number 9) of False (e.g., for 45).

Here, the 1..$n.sqrt range is first repeated twice (xx 2). Look at what it gives on an isolated example:

$ raku -e'dd (1..3) xx 2'
(1..3, 1..3).Seq

Then, the [X**] operator computes the power in all possible combinations:

$ raku -e'dd [X**] (1..3) xx 2'
(1, 1, 1, 2, 4, 8, 3, 9, 27).Seq

Finally, we look if the given number exists in this sequence: $n ∈ . . ..

2

Now, let us print the numbers of the possible solution as the original task requires. Use the same approach but in a bit brute-forced style using the loop over two arrays:

my $n = 9;
# my $n = 45;

for [X] (1..$n.sqrt) xx 2 -> ($x, $y) {
    say "$x^$y" and exit if $n == $x ** $y;
}

say 0;

If the solution is found, we print it and exit the program. Otherwise, print 0.

3

What is still missing, is the case when there are more than a single solution. For example, for 81:

my $n = 81;

for [X] (1..$n.sqrt) xx 2 -> ($x, $y) {
    say "$x^$y" if $n == $x ** $y;
}

How to elegantly print 0 if there is no solution? This is my homework for you. My quick solution would be the following:

say (gather {
    for [X] (1..$n.sqrt) xx 2 -> ($x, $y) {
        take "$x^$y" if $n == $x ** $y;
    }
} || 0).join(', ');

For the input number 81, it prints 3^4, 9^2.

Look for the source code of the above examples on GitHub.

* * *

P. S. My posts in this series, Raku challenges, are aimed to train the ability of creating solutions directly from your head without spending more than half an hour for both the solution and its description. It may be incomplete, slightly incorrect or not optimal, but it allows to quickly pick the appropriate elements from the vast spectre of Raku features.

Navigation to the Raku challenges post series

One thought on “Check if the number can be represented as a power of integers”

Leave a Reply

Your email address will not be published. Required fields are marked *