Encontrar la suma de los dígitos de un número hasta que la suma se convierta en un solo dígito

Encontrar la suma de los dígitos de un número hasta que la suma se convierta en un solo dígito
Pruébalo en GfG Practice

Dado un número entero n, necesitamos encontrar repetidamente la suma de sus dígitos hasta que el resultado sea un número de un solo dígito.

Ejemplos:

Aporte: norte = 1234
Producción: 1
Explicación:
Paso 1: 1 + 2 + 3 + 4 = 10
Paso 2: 1 + 0 = 1

Aporte: norte = 5674
Producción: 4
Explicación:
Paso 1: 5 + 6 + 7 + 4 = 22
Paso 2: 2 + 2 = 4

Tabla de contenido

[Enfoque ingenuo] Agregando dígitos repetidamente

El enfoque se centra en calcular el espacio digital. t de un número que es el resultado de sumar los dígitos repetidamente hasta obtener un valor de un solo dígito. Así es como funciona conceptualmente:

  1. Sumar los dígitos : Comience sumando todos los dígitos del número dado.
  2. Comprueba el resultado : Si la suma es un número de un solo dígito (es decir, menos de 10), deténgase y devuélvalo.
  3. Repetir el proceso : Si la suma aún es más de un dígito, repita el proceso con la suma de dígitos. Esto continúa hasta que se alcanza una suma de un solo dígito.
C++
   // C++ program to find the digit sum by    // repetitively Adding its digits   #include          using     namespace     std  ;   int     singleDigit  (  int     n  )     {      int     sum     =     0  ;      // Repetitively calculate sum until      // it becomes single digit      while     (  n     >     0     ||     sum     >     9  )     {      // If n becomes 0 reset it to sum       // and start a new iteration.      if     (  n     ==     0  )     {      n     =     sum  ;      sum     =     0  ;      }      sum     +=     n     %     10  ;      n     /=     10  ;      }      return     sum  ;   }   int     main  ()     {      int     n     =     1234  ;      cout      < <     singleDigit  (  n  );      return     0  ;   }   
C
   // C program to find the digit sum by    // repetitively Adding its digits   #include         int     singleDigit  (  int     n  )     {      int     sum     =     0  ;      // Repetitively calculate sum until      // it becomes single digit      while     (  n     >     0     ||     sum     >     9  )     {      // If n becomes 0 reset it to sum       // and start a new iteration.      if     (  n     ==     0  )     {      n     =     sum  ;      sum     =     0  ;      }      sum     +=     n     %     10  ;      n     /=     10  ;      }      return     sum  ;   }   int     main  ()     {      int     n     =     1234  ;      printf  (  '%d'       singleDigit  (  n  ));      return     0  ;   }   
Java
   // Java program to find the digit sum by    // repetitively Adding its digits   class   GfG     {      static     int     singleDigit  (  int     n  )     {      int     sum     =     0  ;      // Repetitively calculate sum until      // it becomes single digit      while     (  n     >     0     ||     sum     >     9  )     {      // If n becomes 0 reset it to sum       // and start a new iteration.      if     (  n     ==     0  )     {      n     =     sum  ;      sum     =     0  ;      }      sum     +=     n     %     10  ;      n     /=     10  ;      }      return     sum  ;      }      public     static     void     main  (  String  []     args  )     {      int     n     =     1234  ;      System  .  out  .  println  (  singleDigit  (  n  ));      }   }   
Python
   # Python program to find the digit sum by    # repetitively Adding its digits   def   singleDigit  (  n  ):   sum   =   0   # Repetitively calculate sum until   # it becomes single digit   while   n   >   0   or   sum   >   9  :   # If n becomes 0 reset it to sum    # and start a new iteration   if   n   ==   0  :   n   =   sum   sum   =   0   sum   +=   n   %   10   n   //=   10   return   sum   if   __name__   ==   '__main__'  :   n   =   1234   print  (  singleDigit  (  n  ))   
C#
   // C# program to find the digit sum by    // repetitively Adding its digits   using     System  ;   class     GfG     {      static     int     singleDigit  (  int     n  )     {      int     sum     =     0  ;      // Repetitively calculate sum until      // it becomes single digit      while     (  n     >     0     ||     sum     >     9  )     {      // If n becomes 0 reset it to sum       // and start a new iteration.      if     (  n     ==     0  )     {      n     =     sum  ;      sum     =     0  ;      }      sum     +=     n     %     10  ;      n     /=     10  ;      }      return     sum  ;      }      static     void     Main  ()     {      int     n     =     1234  ;      Console  .  WriteLine  (  singleDigit  (  n  ));      }   }   
JavaScript
   // JavaScript program to find the digit sum by    // repetitively Adding its digits   function     singleDigit  (  n  )     {      let     sum     =     0  ;      // Repetitively calculate sum until      // it becomes single digit      while     (  n     >     0     ||     sum     >     9  )     {      // If n becomes 0 reset it to sum       // and start a new iteration.      if     (  n     ===     0  )     {      n     =     sum  ;      sum     =     0  ;      }      sum     +=     n     %     10  ;      n     =     Math  .  floor  (  n     /     10  );      }      return     sum  ;   }   // Driver Code   const     n     =     1234  ;   console  .  log  (  singleDigit  (  n  ));   

Producción
1 

Complejidad del tiempo: O(registro 10 n) mientras iteramos sobre los dígitos del número.
Espacio Auxiliar: O(1)

[Enfoque esperado] Uso de fórmulas matemáticas

Sabemos que cada número en el sistema decimal se puede expresar como la suma de sus dígitos multiplicada por potencias de 10. Por ejemplo, un número representado como abcd se puede escribir de la siguiente manera:

abcd = a*10^3 + b*10^2 + c*10^1 + d*10^0

Podemos separar los dígitos y reescribir esto como:
abcd = a + b + c + d + (a*999 + b*99 + c*9)
abcd = a + b + c + d + 9*(a*111 + b*11 + c)

Esto implica que cualquier número se puede expresar como la suma de sus dígitos más un múltiplo de 9.
Entonces si tomamos módulo con 9 en cada lado
abcd % 9 = (a + b + c + d) % 9 + 0

Esto significa que el resto cuando abcd se divide por 9 es igual al resto cuando la suma de sus dígitos (a + b + c + d) se divide por 9.


Para saber sobre la implementación del código Consulte Raíz digital (suma digital repetida) del entero grande dado