Problem 29 : Distinct powers
Consider all integer combinations of ab for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5:
22=4, 23=8, 24=16, 25=32
32=9, 33=27, 34=81, 35=243
42=16, 43=64, 44=256, 45=1024
52=25, 53=125, 54=625, 55=3125
If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms:
4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125
How many distinct terms are in the sequence generated by ab for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100?
C++ source code
#include <iostream>
#include <set>
#include <string>
#include <cassert>
using namespace std;
class PE0029
{
private:
static const int MAX_DIGITS = 256;
int m_digitsArray[MAX_DIGITS+1];
void myPower(int a, int b);
void adjustDigitsArray();
string getPowerDigitsString(int a, int b); // a^b
public:
int getDistinctPowersSeq(int x, int y);
};
void PE0029::adjustDigitsArray()
{
for(int j=0; j<MAX_DIGITS-1; j++)
{
m_digitsArray[j+1] += m_digitsArray[j]/10;
m_digitsArray[j] %= 10;
}
}
void PE0029::myPower(int a, int b) // a^b
{
for(int j=0; j<MAX_DIGITS; j++)
{
m_digitsArray[j] = 0;
}
m_digitsArray[0] = 1;
for(int i=1; i<=b; i++)
{
for(int j=0; j<MAX_DIGITS; j++)
{
m_digitsArray[j] *= a;
}
adjustDigitsArray();
}
}
string PE0029::getPowerDigitsString(int a, int b) // a^b
{
char m_digitsString[MAX_DIGITS+1];
myPower(a, b); // a^b, digits are in m_digitsArray[]
for(int i=0; i<MAX_DIGITS; i++)
{
m_digitsString[i] = (char)(m_digitsArray[i]+'0'); // 0 -> '0', 1 -> '1'
}
string digitsString;
digitsString.append(m_digitsString);
return digitsString;
}
int PE0029::getDistinctPowersSeq(int x, int y)
{
set<string> distinctPowers;
string digitsString;
for (int a=2; a<=x; a++)
{
for(int b=2; b<=y; b++)
{
digitsString = getPowerDigitsString(a, b);
distinctPowers.insert(digitsString);
}
}
return distinctPowers.size();
}
int main()
{
PE0029 pe0029;
assert(15 == pe0029.getDistinctPowersSeq(5, 5));
cout << pe0029.getDistinctPowersSeq(100, 100) << " distinct terms are in ";
cout << "the sequence generated by a^b for 2<=a<=100 and 2<=b<=100 " << endl;
return 0;
}
Python source code
def getDistinctPowersSeq(x, y):
distinctPowersArray = []
for a in range(2, x+1):
for b in range(2, y+1):
distinctPowersArray += [int(pow(a,b))]
return len(list(set(distinctPowersArray)))
def main():
assert 15 == getDistinctPowersSeq(5, 5)
print(getDistinctPowersSeq(100, 100),"distinct terms are in the sequence")
print("generated by a^b for 2<=a<=100 and 2<=b<=100 ")
if __name__ == '__main__':
main()