Te dan un número grande de n dígitos, tienes que comprobar si es divisible por 7.
Un número entero de (r+1) dígitos n cuya forma digital es (ar ar-1 ar-2….a2 a1 a0) es divisible por 7 si y solo si la serie alterna de números (a2 a1 a0) – (a5 a4 a3) + (a8 a7 a6) – … es divisible por 7.
Los tripletes de dígitos entre paréntesis representan un número de 3 dígitos en forma digital.
El número dado n se puede escribir como una suma de potencias de 1000 de la siguiente manera.
n= (a2 a1 a0) + (a5 a4 a3)*1000 + (a8 a7 a6)*(1000*1000) +….
Como 1000 = (-1)(mod 7), 1000 según relación de congruencia.
Para un entero positivo n, se dice que dos números a y b son congruentes módulo n, si su diferencia
(a – b) es un múltiplo entero de n (es decir, si hay un entero k tal que a – b = kn ). Esta relación de congruencia normalmente se considera cuando a y b son números enteros, y se denota.
Por lo tanto, podemos escribir:
n = { (a2a1a0) + (a5a4a3)* (-1) + (a8a7a6)* (-1)*(-1) +…..}(mod 7),
Por lo tanto, n es divisible por 7 si y solo si la serie es divisible por 7.
Ejemplos:
Input : 8955795758 Output : Divisible by 7 Explanation: We express the number in terms of triplets of digits as follows. (008)(955)(795)(758) Now, 758- 795 + 955 - 8 = 910, which is divisible by 7 Input : 100000000000 Output : Not Divisible by 7 Explanation: We express the number in terms of triplets of digits as follows. (100)(000)(000)(000) Now, 000- 000 + 000 - 100 = -100, which is not divisible by 7
Tenga en cuenta que el número de dígitos en n puede no ser múltiplo de 3. En ese caso, pasamos cero(s) en el lado izquierdo de los dígitos restantes después de sacar todos los tripletes (del lado derecho de n) para formar el último triplete.
Un método simple y eficiente es tomar la entrada en forma de string (haga su longitud en forma de 3*m agregando 0 a la izquierda del número si es necesario) y luego debe agregar los dígitos en bloques de tres desde la derecha hacia la izquierda hasta que se convierta en un número de 3 dígitos para formar una serie alterna y verificar si la serie es divisible por 7 o no.
Aquí se realiza la implementación del programa para comprobar la divisibilidad de 7.
C++
// C++ code to check divisibility of a // given large number by 7 #include<bits/stdc++.h> using namespace std; int isdivisible7(string num) { int n = num.length(), gSum=0; if (n == 0) return 1; // Append required 0s at the beginning. if (n % 3 == 1) { num="00" + num; n += 2; } else if (n % 3 == 2) { num= "0" + num; n++; } // add digits in group of three in gSum int i, GSum = 0, p = 1; for (i = n - 1; i >= 0; i--) { // group saves 3-digit group int group = 0; group += num[i--] - '0'; group += (num[i--] - '0') * 10; group += (num[i] - '0') * 100; gSum = gSum + group * p; // generate alternate series of plus // and minus p *= (-1); } return (gSum % 7 == 0); } // Driver code int main() { // Driver method string num= "8955795758"; if (isdivisible7(num)) cout << "Divisible by 7"; else cout << "Not Divisible by 7"; return 0; }
C
// C code to check divisibility of a // given large number by 7 #include <stdio.h> #include <string.h> int isdivisible7(char num[]) { int n = strlen(num), gSum=0; char final[n+3]; if (n == 0 && num[0] == '\n') return 1; // Append required 0s at the beginning. if (n % 3 == 1) { final[0]='0'; final[1]='0'; strcat(final,num); n += 2; } else if (n % 3 == 2) { final[0]='0'; strcat(final,num); n++; } // add digits in group of three in gSum int i, GSum = 0, p = 1; for (i = n - 1; i >= 0; i--) { // group saves 3-digit group int group = 0; group += final[i--] - '0'; group += (final[i--] - '0') * 10; group += (final[i] - '0') * 100; gSum = gSum + group * p; // generate alternate series of plus // and minus p *= (-1); } return (gSum % 7 == 0); } // Driver code int main() { // Driver method char num[] = "8955795758"; if (isdivisible7(num)) printf("Divisible by 7"); else printf("Not Divisible by 7"); return 0; }
Java
// Java code to check divisibility of a given large number by 7 class Test { // Method to check divisibility static boolean isDivisible7(String num) { int n = num.length(); if (n == 0 && num.charAt(0) == '0') return true; // Append required 0s at the beginning. if (n % 3 == 1) num = "00" + num; if (n % 3 == 2) num = "0" + num; n = num.length(); // add digits in group of three in gSum int gSum = 0, p = 1; for (int i = n - 1; i >= 0; i--) { // group saves 3-digit group int group = 0; group += num.charAt(i--) - '0'; group += (num.charAt(i--) - '0') * 10; group += (num.charAt(i) - '0') * 100; gSum = gSum + group * p; // generate alternate series of plus and minus p = p * -1; } // calculate result till 3 digit sum return (gSum % 7 == 0); } // Driver method public static void main(String args[]) { String num = "8955795758"; System.out.println(isDivisible7(num) ? "Divisible by 7" : "Not Divisible by 7"); } }
Python3
# Python 3 code to check divisibility # of a given large number by 7 def isdivisible7(num): n = len(num) if (n == 0 and num[0] == '\n'): return 1 # Append required 0s at the beginning. if (n % 3 == 1) : num = "00" + str(num) n += 2 elif (n % 3 == 2) : num = "0" + str(num) n += 1 # add digits in group of three in gSum GSum = 0 p = 1 i = n-1 while i>=0 : # group saves 3-digit group group = 0 group += ord(num[i]) - ord('0') i -= 1 group += (ord(num[i]) - ord('0')) * 10 i -= 1 group += (ord(num[i]) - ord('0')) * 100 GSum = GSum + group * p # generate alternate series of # plus and minus p *= (-1) i -= 1 return (GSum % 7 == 0) # Driver code if __name__ == "__main__": num = "8955795758" if (isdivisible7(num)): print("Divisible by 7") else : print("Not Divisible by 7") # This code is contributed by ChitraNayal
C#
// C# code to check divisibility of a // given large number by 7 using System; class GFG { // Method to check divisibility static bool isDivisible7(String num) { int n = num.Length; if (n == 0 && num[0] == '0') return true; // Append required 0s at the beginning. if (n % 3 == 1) num = "00" + num; if (n % 3 == 2) num = "0" + num; n = num.Length; // add digits in group of three in gSum int gSum = 0, p = 1; for (int i = n - 1; i >= 0; i--) { // group saves 3-digit group int group = 0; group += num[i--] - '0'; group += (num[i--] - '0') * 10; group += (num[i] - '0') * 100; gSum = gSum + group * p; // generate alternate series // of plus and minus p = p * -1; } // calculate result till 3 digit sum return (gSum % 7 == 0); } // Driver code static public void Main() { String num = "8955795758"; // Function calling Console.WriteLine(isDivisible7(num) ? "Divisible by 7" : "Not Divisible by 7"); } } // This code is contributed by Ajit.
PHP
<?php // PHP code to check divisibility of // a given large number by 7 // Function to check divisibility function isDivisible7($num) { $n = strlen($num) ; if ($n == 0 && $num[0] == '0') return true; // Append required 0s at the beginning. if ($n % 3 == 1) $num = "00" . $num; if ($n % 3 == 2) $num = "0". $num; $n = strlen($num); // add digits in group of three in gSum $gSum = 0 ; $p = 1; for ($i = $n - 1; $i >= 0; $i--) { // group saves 3-digit group $group = 0; $group += $num[$i--] - '0'; $group += ($num[$i--] - '0') * 10; $group += ($num[$i] - '0') * 100; $gSum = $gSum + $group * $p; // generate alternate series // of plus and minus $p = $p * -1; } // calculate result till 3 digit sum return ($gSum % 7 == 0); } // Driver Code $num = "8955795758"; echo (isDivisible7($num) ? "Divisible by 7" : "Not Divisible by 7"); // This code is contributed by Ryuga ?>
Javascript
<script> // Javascript code to check divisibility of // a given large number by 7 // Function to check divisibility function isDivisible7(num) { let n = num.length; if (n == 0 && num[0] == '0') return true; // Append required 0s at the beginning. if (n % 3 == 1) num = "00" + num; if (n % 3 == 2) num = "0" + num; n = num.length; // Add digits in group of three in gSum gSum = 0 ; let p = 1; for(let i = n - 1; i >= 0; i--) { // Group saves 3-digit group group = 0; group += num[i--] - '0'; group += (num[i--] - '0') * 10; group += (num[i] - '0') * 100; gSum = gSum + group * p; // Generate alternate series // of plus and minus p = p * -1; } // Calculate result till 3 digit sum return (gSum % 7 == 0); } // Driver Code let num = "8955795758"; document.write(isDivisible7(num) ? "Divisible by 7" : "Not Divisible by 7"); // This code is contributed by _saurabh_jaiswal </script>
Divisible by 7
Método 2: Verificar que el número dado es divisible por 7 o no usando el operador de división de módulo «%».
C++
#include <iostream> using namespace std; int main() { //input long long int n=100000000000; // finding given number is divisible by 7 or not if (n%7==0) { cout << "Yes"; } else { cout << "No"; } return 0; }
Java
// Java code // To check whether the given number is divisible by 7 or not import java.io.*; import java.util.*; class GFG { public static void main(String[] args) { //input long n=100000000000L; // 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)%7==0) { System.out.println("Yes"); } else { System.out.println("No"); } } } //this code is contributed by aditya942003patil
Python3
# Python code # To check whether the given number is divisible by 7 or not #input n=100000000000 # the above input can also be given as n=input() -> taking input from user # finding given number is divisible by 7 or not if int(n)%7==0: print("Yes") else: print("No") # this code is contributed by gangarajula laxmi
C#
// c# code to check whether the given // number is diivisible by 7 or not using System; public class GFG { public static void Main() { //input long n=100000000000; // 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%7==0) { Console.Write("Yes"); } else { Console.Write("No"); } } } // This code is contributed by aditya942003patil
Javascript
<script> // JavaScript code for the above approach // To check whether the given number is divisible by 7 or not //input var n = 100000000000 // 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 % 7 == 0) document.write("Yes") else document.write("No") // This code is contributed by Potta Lokesh </script>
PHP
<?php //input $n=100000000000; // 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%7==0) { echo "Yes"; } else { echo "No"; } // This code is contributed by laxmigangarajula03 ?>
No
Este artículo es una contribución de Sruti Rai . 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