Dado un número, la tarea es verificar si un número es divisible por 4 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 = 1124 Output : Yes Input : n = 1234567589333862 Output : No Input : n = 363588395960667043875487 Output : No
Dado que el número de entrada puede ser muy grande, no podemos usar n % 4 para verificar si un número es divisible por 4 o no, especialmente en lenguajes como C/C++. La idea se basa en el siguiente hecho.
Un número es divisible por 4 si el número formado por sus dos últimas cifras es divisible por 4.
Ilustración:
For example, let us consider 76952 Number formed by last two digits = 52 Since 52 is divisible by 4, answer is YES.
¿Como funciona esto?
Let us consider 76952, we can write it as 76942 = 7*10000 + 6*1000 + 9*100 + 5*10 + 2 The proof is based on below observation: Remainder of 10i divided by 4 is 0 if i greater than or equal to two. Note than 100, 1000, ... etc lead to remainder 0 when divided by 4. So remainder of "7*10000 + 6*1000 + 9*100 + 5*10 + 2" divided by 4 is equivalent to remainder of following : 0 + 0 + 0 + 5*10 + 2 = 52 Therefore we can say that the whole number is divisible by 4 if 52 is divisible by 4.
A continuación se muestra la implementación de la idea anterior:
C++
// C++ program to find if a number is divisible by // 4 or not #include <bits/stdc++.h> using namespace std; // Function to find that number divisible by // 4 or not bool check(string str) { int n = str.length(); // Empty string if (n == 0) return false; // If there is single digit if (n == 1) return ((str[0] - '0') % 4 == 0); // If number formed by last two digits is // divisible by 4. int last = str[n - 1] - '0'; int second_last = str[n - 2] - '0'; return ((second_last * 10 + last) % 4 == 0); } // Driver code int main() { string str = "76952"; // Function call check(str) ? cout << "Yes" : cout << "No "; return 0; }
Java
// Java program to find if a number is // divisible by 4 or not class IsDivisible { // Function to find that number // is divisible by 4 or not static boolean check(String str) { int n = str.length(); // Empty string if (n == 0) return false; // If there is single digit if (n == 1) return ((str.charAt(0) - '0') % 4 == 0); // If number formed by last two digits is // divisible by 4. int last = str.charAt(n - 1) - '0'; int second_last = str.charAt(n - 2) - '0'; return ((second_last * 10 + last) % 4 == 0); } // Driver code public static void main(String[] args) { String str = "76952"; // Function call if (check(str)) System.out.println("Yes"); else System.out.println("No"); } }
Python3
# Python 3 program to find # if a number is divisible # by 4 or not # Function to find that # number divisible by # 4 or not def check(st): n = len(st) # Empty string if (n == 0): return False # If there is single # digit if (n == 1): return ((st[0] - '0') % 4 == 0) # If number formed by # last two digits is # divisible by 4. last = (int)(st[n - 1]) second_last = (int)(st[n - 2]) return ((second_last * 10 + last) % 4 == 0) # Driver code st = "76952" # Function call 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 4 or not using System; class GFG { // Function to find that number // is divisible by 4 or not static bool check(String str) { int n = str.Length; // Empty string if (n == 0) return false; // If there is single digit if (n == 1) return ((str[0] - '0') % 4 == 0); // If number formed by last two // digits is divisible by 4. int last = str[n - 1] - '0'; int second_last = str[n - 2] - '0'; return ((second_last * 10 + last) % 4 == 0); } // Driver code public static void Main() { String str = "76952"; // Function call 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 // 4 or not // Function to find that // number divisible by // 4 or not function check($str) { $n = strlen($str); // Empty string if ($n == 0) return false; // If there is single digit if ($n == 1) return (($str[0] - '0') % 4 == 0); // If number formed by // last two digits is // divisible by 4. $last = $str[$n - 1] - '0'; $second_last = $str[$n - 2] - '0'; return (($second_last * 10 + $last) % 4 == 0); } // Driver code $str = "76952"; // Function call $x = check($str)? "Yes" : "No"; echo($x); // This code is contributed by Ajit. ?>
Javascript
//Javascript program to check whether a string is divisible by 4 or not // function to check the divisibility function check(str) { // checking the length for future reference var n = str.length; // if it is empty then directly returning false if( n == 0) { return false; } if( n == 1) { return ((str[0] -'0') % 4 == 0); } var lastNumber = str[n-1] -'0'; var lastSecondNUmber = str[n-2] -'0'; return ((lastSecondNUmber * 10 + lastNumber) % 4 == 0); } // Driver code var str="76952"; //checking the value by passing it into the function // Function call if(check(str)){ console.log("Yes"); } else{ console.log("No"); }
Yes
Complejidad de tiempo : O (1), ya que no estamos usando ningún bucle para atravesar.
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 4 o no mediante el operador de división de módulo «%».
Python3
# Python code # To check whether the given number is divisible by 4 or not #input n=1234567589333862 # the above input can also be given as n=input() -> taking input from user # finding given number is divisible by 4 or not if int(n)%4==0: print("Yes") else: print("No") # this code is contributed by gangarajula laxmi
C#
using System; public class GFG{ static public void Main (){ // input long n=1234567589333862; // the above input can also be given as n=input() -> taking input from user // finding given number is divisible by 7 or not if (n % 4 == 0) { Console.Write("Yes"); } else { Console.Write("No"); } } } // This code is contributed by laxmigangarajula03
Javascript
<script> // JavaScript code for the above approach // To check whether the given number is divisible by 4 or not //input var n = 1234567589333862 // finding given number is divisible by 4 or not if (n % 4 == 0) document.write("Yes") else document.write("No") // This code is contributed by Potta Lokesh </script>
No
Complejidad de tiempo : O (1), ya que no estamos usando ningún bucle para atravesar.
Espacio auxiliar: O(1), ya que no estamos utilizando ningún espacio adicional.
Método 3: Uso de la función incorporada Atoi() en C++.
La función atoi() en C++ toma una string (que representa un número entero) como argumento y devuelve su valor de tipo int. Entonces, básicamente, la función se usa para convertir un argumento de string en un número entero.
Sintaxis:
int atoi(const char str)
Parámetros: la función acepta un parámetro str que se refiere al argumento de string que se necesita convertir en su equivalente entero.
Valor devuelto: si str es una entrada válida, la función devuelve el número entero equivalente para el número de string pasado. Si no tiene lugar una conversión válida, la función devuelve cero.
Implementación
C++
// C++ program to find if a number is divisible by // 4 or not #include <bits/stdc++.h> using namespace std; // Driver code int main() { char str[] = "76952"; int n = (sizeof(str) / sizeof(char))-1; char ch[2]; if (n >= 2) { ch[0] = str[n - 2]; ch[1] = str[n - 1]; } else if (n == 1) { ch[0] = 0; ch[1] = str[0]; } int x; x = atoi(ch); if (!(x % 4)) { cout << "YES"; } else { cout << "NO"; } return 0; } // This code is contributed by Aarti_Rathi
YES
Complejidad de tiempo : O (1), ya que no estamos usando ningún bucle para atravesar.
Espacio auxiliar: O(1), ya que no estamos utilizando ningún espacio adicional.
Método 4: (usando la función de substring)
- Utilice la función de substring para obtener los dos últimos caracteres de la string.
- Convertir la string a entero
- Comprueba si es divisible por 4 o no, usando (número%4 == 0).
Este enfoque es aportado por Abhijeet Kumar .
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ program to find if a number is divisible by // 4 or not #include <bits/stdc++.h> using namespace std; // Function to find that number divisible by // 4 or not bool check(string str) { // Get the length of the string int n = str.length(); // Empty string if (n == 0) return false; // stoi(string_variable) is used in C++ // to convert string to integer // If there is single digit if (n == 1) return ((stoi(str)) % 4 == 0); // getting last two characters using substring str = str.substr(n - 2, 2); // If number formed by last two digits is // divisible by 4. return ((stoi(str)) % 4 == 0); } // Driver code int main() { string str = "76952"; // Function call check(str) ? cout << "Yes" : cout << "No "; return 0; } // This code is contributed by Abhijeet Kumar(abhijeet19403)
Java
// Java program to find if a number is // divisible by 4 or not class IsDivisible { // Function to find that number // is divisible by 4 or not static boolean check(String str) { // Get the length of the string int n = str.length(); // Empty string if (n == 0) return false; // Integer.parseInt(string_variable) is used in Java // to convert string to integer // If there is single digit if (n == 1) return ((Integer.parseInt(str)) % 4 == 0); // getting last two characters using substring str = str.substring(n - 2); // If number formed by last two digits is // divisible by 4. return ((Integer.parseInt(str)) % 4 == 0); } // Driver code public static void main(String[] args) { String str = "76952"; // Function call if (check(str)) System.out.println("Yes"); else System.out.println("No"); } } // This code is contributed by Abhijeet Kumar(abhijeet19403)
Python3
# Python 3 program to find # if a number is divisible # by 4 or not # Function to find that # number divisible by # 4 or not def check(st): n = len(st) # Empty string if (n == 0): return False # int(string_variable) is used in Python3 # to convert string to integer # If there is single # digit if (n == 1): return (int(st) % 4 == 0) # slicing of strings is used in Python to function as substring st = st[n-2:] # If number formed by # last two digits is # divisible by 4. return (int(st) % 4 == 0) # Driver code st = "76952" # Function call if(check(st)): print("Yes") else: print("No ") # This code is contributed by Abhijeet Kumar(abhijeet19403)
C#
// C# program to find if a number is // divisible by 4 or not using System; class GFG { // Function to find that number // is divisible by 4 or not static bool check(String str) { int n = str.Length; // Empty string if (n == 0) return false; // int.Parse(string_variable) is used in C# // to convert string to integer // If there is single digit if (n == 1) return (int.Parse(str) % 4 == 0); // getting last two characters using substring str = str.Substring(n-2); // If number formed by last two // digits is divisible by 4. return (int.Parse(str) % 4 == 0); } // Driver code public static void Main() { String str = "76952"; // Function call if (check(str)) Console.Write("Yes"); else Console.Write("No"); } } // This code is Contributed by Abhijeet Kumar(abhijeet19403)
Javascript
//Javascript program to check whether a string is divisible by 4 or not // function to check the divisibility function check(str) { // checking the length for future reference var n = str.length; // if it is empty then directly returning false if( n == 0) { return false; } // parseInt(string_variable) is used in Javascript // to convert string to integer if( n == 1) { return (parseInt(str) % 4 == 0); } // getting last two characters using substring str = str.substring(n-2); // If number formed by last two digits is // divisible by 4. return (parseInt(str) % 4 == 0); } // Driver code var str="76952"; //checking the value by passing it into the function // Function call if(check(str)){ console.log("Yes"); } else{ console.log("No"); } // This code is contributed by Abhijeet Kumar(abhijeet19403)
Yes
Complejidad de tiempo: (1)
La función de substring toma el tiempo O(n), donde n es la longitud de la substring y como aquí n es igual a 2, la complejidad del tiempo es constante.
Espacio Auxiliar: O(1)
Como espacio adicional constante se utiliza.
Este artículo es una contribución de Aarti_Rathi y 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