Comprobar si un número grande es divisible por 11 o no

Dado un número, la tarea es verificar si el número es divisible por 11 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 = 76945
Output : Yes

Input  : n = 1234567589333892
Output : Yes

Input  : n = 363588395960667043875487
Output : No

Dado que el número de entrada puede ser muy grande, no podemos usar n % 11 para verificar si un número es divisible por 11 o no, especialmente en lenguajes como C/C++. La idea se basa en el siguiente hecho.
Un número es divisible por 11 si la diferencia de los dos siguientes es divisible por 11. 
 

  1. Suma de dígitos en lugares impares.
  2. Suma de dígitos en lugares pares.

Ilustración: 
 

For example, let us consider 76945 
Sum of digits at odd places  : 7 + 9 + 5
Sum of digits at even places : 6 + 4 
Difference of two sums = 21 - 10 = 11
Since difference is divisible by 11, the
number 7945 is divisible by 11.

¿Como funciona esto? 

Let us consider 7694, we can write it as
7694 = 7*1000 + 6*100 + 9*10 + 4

The proof is based on below observation:
Remainder of 10i divided by 11 is 1 if i is even
Remainder of 10i divided by 11 is -1 if i is odd

So the powers of 10 only result in values either 1 
or -1. 

Remainder of "7*1000 + 6*100 + 9*10 + 4"
divided by 11 can be written as : 
7*(-1) + 6*1 + 9*(-1) + 4*1

The above expression is basically difference 
between sum of even digits and odd digits.

A continuación se muestra la implementación del hecho anterior:
 

C++

// C++ program to find if a number is divisible by
// 11 or not
#include<bits/stdc++.h>
using namespace std;
 
// Function to find that number divisible by 11 or not
int check(string str)
{
    int n = str.length();
 
    // Compute sum of even and odd digit
    // sums
    int oddDigSum = 0, evenDigSum = 0;
    for (int i=0; i<n; i++)
    {
        // When i is even, position of digit is odd
        if (i%2 == 0)
            oddDigSum += (str[i]-'0');
        else
            evenDigSum += (str[i]-'0');
    }
 
    // Check its difference is divisible by 11 or not
    return ((oddDigSum - evenDigSum) % 11 == 0);
}
 
// Driver code
int main()
{
    string str = "76945";
    check(str)?  cout << "Yes" : cout << "No ";
    return 0;
}

Java

// Java program to find if a number is
// divisible by 11 or not
class IsDivisible
{
    // Function to find that number divisible by 11 or not
    static boolean check(String str)
    {
        int n = str.length();
      
        // Compute sum of even and odd digit
        // sums
        int oddDigSum = 0, evenDigSum = 0;
        for (int i=0; i<n; i++)
        {
            // When i is even, position of digit is odd
            if (i%2 == 0)
                oddDigSum += (str.charAt(i)-'0');
            else
                evenDigSum += (str.charAt(i)-'0');
        }
      
        // Check its difference is divisible by 11 or not
        return ((oddDigSum - evenDigSum) % 11 == 0);
    }
     
    // main function
    public static void main (String[] args)
    {
        String str = "76945";
        if(check(str))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}

Python3

# Python 3 code program to find if a number
# is divisible by 11 or not
 
 
# Function to find that number divisible by
#  11 or not
def check(st) :
    n = len(st)
 
    # Compute sum of even and odd digit
    # sums
    oddDigSum = 0
    evenDigSum = 0
    for i in range(0,n) :
        # When i is even, position of digit is odd
        if (i % 2 == 0) :
            oddDigSum = oddDigSum + ((int)(st[i]))
        else:
            evenDigSum = evenDigSum + ((int)(st[i]))
     
     
    # Check its difference is divisible by 11 or not
    return ((oddDigSum - evenDigSum) % 11 == 0)
 
# Driver code
st = "76945"
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 11 or not
using System;
 
class GFG
{
    // Function to find that number
    // divisible by 11 or not
    static bool check(string str)
    {
        int n = str.Length;
     
        // Compute sum of even and odd digit
        // sums
        int oddDigSum = 0, evenDigSum = 0;
         
        for (int i = 0; i < n; i++)
        {
            // When i is even, position of
            // digit is odd
            if (i % 2 == 0)
                oddDigSum += (str[i] - '0');
            else
                evenDigSum += (str[i] - '0');
        }
     
        // Check its difference is
        // divisible by 11 or not
        return ((oddDigSum - evenDigSum)
                                % 11 == 0);
    }
     
    // main function
    public static void Main ()
    {
        String str = "76945";
         
        if(check(str))
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
    }
}
 
// This code is contributed by vt_m.

PHP

<?php
// PHP program to find if a
// number is divisible by
// 11 or not
 
// Function to find that number
// divisible by 11 or not
function check($str)
{
    $n = strlen($str);
 
    // Compute sum of even
    // and odd digit sums
    $oddDigSum = 0; $evenDigSum = 0;
    for ($i = 0; $i < $n; $i++)
    {
         
        // When i is even, position
        // of digit is odd
        if ($i % 2 == 0)
            $oddDigSum += ($str[$i] - '0');
        else
            $evenDigSum += ($str[$i] - '0');
    }
 
    // Check its difference
    // is divisible by 11 or not
    return (($oddDigSum - $evenDigSum)
                            % 11 == 0);
}
 
// Driver code
$str = "76945";
$x = check($str)? "Yes" : "No ";
echo($x);
 
// This code is contributed by Ajit.
?>

Javascript

<script>
 
// JavaScript program for the above approach
 
    // Function to find that number
    // divisible by 11 or not
    function check(str)
    {
        let n = str.length;
     
        // Compute sum of even and odd digit
        // sums
        let oddDigSum = 0, evenDigSum = 0;
         
        for (let i = 0; i < n; i++)
        {
         
            // When i is even, position of
            // digit is odd
            if (i % 2 == 0)
                oddDigSum += (str[i] - '0');
            else
                evenDigSum += (str[i] - '0');
        }
     
        // Check its difference is
        // divisible by 11 or not
        return ((oddDigSum - evenDigSum)
                                % 11 == 0);
    }
     
// Driver Code
    let str = "76945";
    if(check(str))
        document.write("Yes");
    else
        document.write("No");
         
// This code is contributed by chinmoy1997pal.
</script>
Producción

Yes

Complejidad de tiempo : O(logN), donde N es el número dado.

Espacio auxiliar : O(1), ya que no estamos utilizando ningún espacio adicional.

Método: Comprobación de que el número dado es divisible por 11 o no mediante el operador de división de módulo «%».  

Python3

# Python code
# To check whether the given number is divisible by 11 or not
 
#input
n=1234567589333892
# the above input can also be given as n=input() -> taking input from user
# finding given number is divisible by 11 or not
if int(n)%11==0:
  print("Yes")
else:
  print("No")
 
  # this code is contributed by gangarajula laxmi
Producción

Yes

Método: Comprobar que el número dado es divisible por 11 o no usar la división de módulo.

C++

// C++ program to check if given number is divisible by 11
// or not using modulo division
 
#include <iostream>
using namespace std;
 
int main()
{
 
    // input number
    int num = 76945;
    // checking if the given number is divisible by 11 or
    // not using modulo division operator if the output of
    // num%11 is equal to 0 then given number is divisible
    // by 11 otherwise not divisible by 11
    if (num % 11 == 0) {
        cout << " divisible";
    }
    else {
        cout << " not divisible";
    }
    return 0;
}
 
// this code is contributed by gangarajula laxmi

Java

// java program to check if given number is divisible by 11
// or not using modulo division
 
import java.io.*;
 
class GFG {
    public static void main(String[] args)
    {
        // input number
        int num = 76945;
        // checking if the given number is divisible by 11
        // or not
        // using modulo division operator if the output of
        // num%11 is equal to 0 then given number is
        // divisible by 11 otherwise not divisible by 11
        if (num % 11 == 0) {
            System.out.println(" divisible");
        }
        else {
            System.out.println(" not divisible");
        }
    }
}
 
// this code is contributed by gangarajula laxmi
Producción

 divisible

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

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *