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