How to resolve the algorithm First perfect square in base n with n unique digits step by step in the D programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm First perfect square in base n with n unique digits step by step in the D programming language
Table of Contents
Problem Statement
Find the first perfect square in a given base N that has at least N digits and exactly N significant unique digits when expressed in base N. E.G. In base 10, the first perfect square with at least 10 unique digits is 1026753849 (32043²). You may use analytical methods to reduce the search space, but the code must do a search. Do not use magic numbers or just feed the code the answer to verify it is correct.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm First perfect square in base n with n unique digits step by step in the D programming language
Source code in the d programming language
import std.algorithm;
import std.exception;
import std.math;
import std.stdio;
import std.string;
string toBaseN(const long num, const int base)
in (base > 1, "base cannot be less than 2")
body {
immutable ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
enforce(base < ALPHABET.length, "base cannot be represented");
char[] result;
long cnum = abs(num);
while (cnum > 0) {
auto rem = cast(uint) (cnum % base);
result ~= ALPHABET[rem];
cnum = (cnum - rem) / base;
}
if (num < 0) {
result ~= '-';
}
return result.reverse.idup;
}
int countUnique(string buf) {
bool[char] m;
foreach (c; buf) {
m[c] = true;
}
return m.keys.length;
}
void find(int base) {
long nmin = cast(long) pow(cast(real) base, 0.5 * (base - 1));
for (long n = nmin; /*blank*/; n++) {
auto sq = n * n;
enforce(n * n > 0, "Overflowed the square");
string sqstr = toBaseN(sq, base);
if (sqstr.length >= base && countUnique(sqstr) == base) {
string nstr = toBaseN(n, base);
writefln("Base %2d : Num %8s Square %16s", base, nstr, sqstr);
return;
}
}
}
void main() {
foreach (i; 2..17) {
find(i);
}
}
You may also check:How to resolve the algorithm Eban numbers step by step in the RPL programming language
You may also check:How to resolve the algorithm String case step by step in the Pop11 programming language
You may also check:How to resolve the algorithm Long primes step by step in the M2000 Interpreter programming language
You may also check:How to resolve the algorithm Vector step by step in the Perl programming language
You may also check:How to resolve the algorithm Case-sensitivity of identifiers step by step in the Aime programming language