DEV Community

Sagnik Chatterjee
Sagnik Chatterjee

Posted on

codegolf#1: Niven Numbers

Recently, I cam across Code Golf, a site where people compete for writing the smallest piece of code to solve a challenge and people are ranked according to how many few characters does it take to run the code.

This post describes my solution to solve Niven number challenge in the Code Golf site , where I got the 72th position.😬 not a very good score, but in this challenge I got to experience writing super small functional code.

So the problem statement goes something like this:
A Niven number is a positive integer that is divisible by the sum of its digits.

Print all the Niven numbers from 1 to 10,000 inclusive, each on their own line.


for i in range(1,10001):
Enter fullscreen mode Exit fullscreen mode

First we take the input and convert to string and split it into a list and then us sum on those values. This gives us the sum of digits and then to get the result we check if the mod value is 0. If yes, then we print the value for it.

Top comments (2)

peter919 profile image
Peter919 • Edited

This 93-byte approach seems to work in C (gcc):

main(i,j){for(char s[9],*c;i<10001;i++%j?:puts(s)){itoa(i,s,10);j=0;for(c=s;*c;j+=*c++-48);}}
Enter fullscreen mode Exit fullscreen mode

With comments:

main(i,j) // i and j are integers, i is initialized to 1
        for (char s[9],*c; // s is a string with 9 characters, c is a char pointer
              i<10001; // while i < 10001
              i++%j?:puts(s)) { // at the end of the loop, check if i divided by j has a remainder. if not, print s. i is incremented after the divisibility test

                itoa(i,s,10); // convert i to a string in base 10, store result in s

                j=0; // j will count the digit sum
                for (c=s; // make c point to the first character in s
                     *c; // loop while c isn't a null-terminator
                     j+=*c++-48) // at the end of the loop, add digit to j. 48 is the ascii code for the digit "0". c is also post-incremented, and will point to the next character in s.
                        ; // nothing is done within the loop
Enter fullscreen mode Exit fullscreen mode
adamnielson42 profile image
adamnielson42 • Edited

without actually changing much of the code you can use overloading to remove the if statement, your second line would become