fork(1) download
  1. #include <stdio.h>
  2.  
  3. /* Potęgowanie w integerach: https://e...content-available-to-author-only...a.org/wiki/Exponentiation_by_squaring*/
  4. unsigned long pow(unsigned long a, unsigned long b) {
  5. if (b == 0) return 1;
  6. if (b == 1) return a;
  7. if (b % 2 == 0) return pow(a * a, b / 2);
  8. else return a * pow(a * a, (b - 1) / 2);
  9. }
  10.  
  11. /* Suma cyfr w liczbie, prosta obserwacja: kolejne cyfry liczby n to (od prawej):
  12.  * n % 10
  13.  * n / 10 % 10
  14.  * n / 100 % 10
  15.  * .....
  16.  */
  17. unsigned long sum_digits(unsigned long n){
  18. unsigned long s = 0;
  19. for (unsigned long i = 0; n / pow(10, i) > 0; ++i)
  20. s += (n / pow(10, i)) % 10;
  21. return s;
  22. }
  23.  
  24. /* Proste, rekurencyjne wywoływanie sumy cyfr, aż do
  25.  * przypadku bazowego: liczba jednocyfrowej,
  26.  * wtedy n / 10 == 0
  27.  * */
  28. unsigned long sum_digits_until_one(unsigned long n) {
  29. if (n / 10 == 0) return;
  30. else
  31. return sum_digits_until_one(sum_digits(n));
  32. }
  33.  
  34. int main(int argc, char **argv)
  35. {
  36. printf("%lu \n", sum_digits_until_one(98792) == 8); // -> 1 (true)
  37. printf("%lu \n", sum_digits_until_one(6841) == 1); // -> 1 (true)
  38. return 0;
  39. }
Success #stdin #stdout 0s 4388KB
stdin
Standard input is empty
stdout
0 
0