Dado un número, la tarea es encontrar si el número es divisible por 9 o no. El número de entrada puede ser grande y puede que no sea posible almacenarlo incluso si usamos long long int.
Ejemplos:
Input : n = 69354 Output : Yes Input : n = 234567876799333 Output : No Input : n = 3635883959606670431112222 Output : No
Dado que el número de entrada puede ser muy grande, no podemos usar n % 9 para verificar si un número es divisible por 9 o no, especialmente en lenguajes como C/C++. La idea se basa en el siguiente hecho.
A number is divisible by 9 if sum of its digits is divisible by 9.
Ilustración:
For example n = 9432 Sum of digits = 9 + 4 + 3 + 2 = 18 Since sum is divisible by 9, answer is Yes.
¿Como funciona esto?
Let us consider 1332, we can write it as 1332 = 1*1000 + 3*100 + 3*10 + 2 The proof is based on below observation: Remainder of 10i divided by 9 is 1 So powers of 10 only results in remainder 1 when divided by 9. Remainder of "1*1000 + 3*100 + 3*10 + 2" divided by 9 can be written as : 1*1 + 3*1 + 3*1 + 2 = 9 The above expression is basically sum of all digits. Since 9 is divisible by 9, answer is yes.
A continuación se muestra la implementación de la idea anterior.
C++
// C++ program to find if a number is divisible by // 9 or not #include<bits/stdc++.h> using namespace std; // Function to find that number divisible by 9 or not int check(string str) { // Compute sum of digits int n = str.length(); int digitSum = 0; for (int i=0; i<n; i++) digitSum += (str[i]-'0'); // Check if sum of digits is divisible by 9. return (digitSum % 9 == 0); } // Driver code int main() { string str = "99333"; check(str)? cout << "Yes" : cout << "No "; return 0; }
Java
// Java program to find if a number is // divisible by 9 or not class IsDivisible { // Function to find that number // is divisible by 9 or not static boolean check(String str) { // Compute sum of digits int n = str.length(); int digitSum = 0; for (int i=0; i<n; i++) digitSum += (str.charAt(i)-'0'); // Check if sum of digits is divisible by 9. return (digitSum % 9 == 0); } // main function public static void main (String[] args) { String str = "99333"; if(check(str)) System.out.println("Yes"); else System.out.println("No"); } }
Python3
# Python 3 program to # find if a number is # divisible by # 9 or not # Function to find that # number divisible by 9 # or not def check(st) : # Compute sum of digits n = len(st) digitSum = 0 for i in range(0,n) : digitSum = digitSum + (int)(st[i]) # Check if sum of digits # is divisible by 9. return (digitSum % 9 == 0) # Driver code st = "99333" if(check(st)) : print("Yes") else : print("No") # This code is contributed by Nikita Tiwari.
C#
// C# program to find if a number is // divisible by 9 or not. using System; class GFG { // Function to find that number // is divisible by 9 or not static bool check(String str) { // Compute sum of digits int n = str.Length; int digitSum = 0; for (int i = 0; i < n; i++) digitSum += (str[i] - '0'); // Check if sum of digits is // divisible by 9. return (digitSum % 9 == 0); } // main function public static void Main () { String str = "99333"; if(check(str)) Console.Write("Yes"); else Console.Write("No"); } } // This code is Contributed by // nitin mittal.
PHP
<?php // PHP program to find if a number // is divisible by 9 or not // Function to find that // number divisible by 9 or not function check($str) { // Compute sum of digits $n = strlen($str); $digitSum = 0; for ($i = 0; $i < $n; $i++) $digitSum += ($str[$i] - '0'); // Check if sum of digits // is divisible by 9. return ($digitSum % 9 == 0); } // Driver code $str = "99333"; $x = check($str) ? "Yes" : "No "; echo($x); // This code is contributed by Ajit. ?>
Javascript
<script> // Javascript program to find if a number // is divisible by 9 or not // Function to find that // number divisible by 9 or not function check(str) { // Compute sum of digits let n = str.length; let digitSum = 0; for(let i = 0; i < n; i++) digitSum += (str[i] - '0'); // Check if sum of digits // is divisible by 9. return (digitSum % 9 == 0); } // Driver code let str = "99333"; let x = check(str) ? "Yes" : "No "; document.write(x); // This code is contributed by _saurabh_jaiswal. </script>
Yes
Producción:
Yes
Complejidad de tiempo: O (logN), ya que estamos recorriendo los dígitos, lo que efectivamente costará el tiempo de logN.
Espacio auxiliar: O(1), ya que no estamos utilizando ningún espacio adicional.
Método 2: comprobar que el número dado es divisible por 9 o no mediante el operador de división de módulo «%».
Python3
# Python code # To check whether the given number is divisible by 9 or not #input n=3635883959606670431112222 # the above input can also be given as n=input() -> taking input from user # finding given number is divisible by 9 or not if int(n)%9==0: print("Yes") else: print("No") # this code is contributed by gangarajula laxmi
Javascript
<script> // JavaScript code for the above approach //input var n=3635883959606670431112222 // finding given number is divisible by 9 or not if (n%9==0) document.write("Yes") else document.write("No") // This code is contributed by Potta Lokesh </script>
No
Este artículo es una contribución de DANISH_RAZA . Si te gusta GeeksforGeeks y te gustaría contribuir, también puedes escribir un artículo usando write.geeksforgeeks.org o enviar tu artículo por correo a review-team@geeksforgeeks.org. Vea su artículo que aparece en la página principal de GeeksforGeeks y ayude a otros Geeks.
Escriba comentarios si encuentra algo incorrecto o si desea compartir más información sobre el tema tratado anteriormente.
Publicación traducida automáticamente
Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA