Increasing gaps between consecutive Niven numbers: Difference between revisions

Content added Content deleted
(Added C solution)
m (Minor performance improvement)
Line 116: Line 116:
// Returns the sum of the digits of n given the
// Returns the sum of the digits of n given the
// sum of the digits of n - 1
// sum of the digits of n - 1
uint64_t digit_sum(uint64_t n, int sum)
uint64_t digit_sum(uint64_t n, int sum) {
{
++sum;
++sum;
while (n > 0 && n % 10 == 0)
while (n > 0 && n % 10 == 0) {
{
sum -= 9;
sum -= 9;
n /= 10;
n /= 10;
Line 127: Line 125:
}
}


inline bool divisible(uint64_t n, uint64_t d) {
int main()
if ((d & 1) == 0 && (n & 1) == 1)
{
return false;
return n % d == 0;
}

int main() {
// Print numbers with commas
// Print numbers with commas
std::cout.imbue(std::locale(""));
std::cout.imbue(std::locale(""));
Line 136: Line 139:


std::cout << "Gap index Gap Niven index Niven number\n";
std::cout << "Gap index Gap Niven index Niven number\n";
for (uint64_t niven = 1; gap_index <= 32; ++niven)
for (uint64_t niven = 1; gap_index <= 32; ++niven) {
{
sum = digit_sum(niven, sum);
sum = digit_sum(niven, sum);
if (niven % sum == 0)
if (divisible(niven, sum)) {
{
if (niven > previous + gap) {
if (niven > previous + gap)
{
gap = niven - previous;
gap = niven - previous;
std::cout << std::setw(9) << gap_index++
std::cout << std::setw(9) << gap_index++