Dados dos números consecutivos positivos M y N, la tarea es encontrar la diferencia de cuadrados de los dos números sin calcular el cuadrado de esos números.
Ejemplos:
Entrada: N = 4, M = 5
Salida: 9
Explicación:
5 2 – 4 2 = 25 – 16 = 9.
Entrada: N = 999999999, M = 1000000000
Salida: 1999999999
Planteamiento: La idea es usar la expresión algebraica para resolver este problema. Se da en la pregunta que M = N + 1. Por lo tanto:
- El valor a calcular es M 2 – N 2 .
- Al reemplazar M por N + 1, la ecuación anterior se convierte en:
(N + 1)2 - N2
- (N + 1) 2 se puede expandir a:
N2 + 12 + 2 * N - N2
- Al simplificar, la ecuación anterior se convierte en:
1 + 2 * N 1 + N + N (1 + N) + N M + N
- Por lo tanto, simplemente necesitamos calcular y devolver el valor de M + N.
A continuación se muestra la implementación del enfoque anterior:
CPP
// C++ program to find the square // difference of two large // consecutive numbers #include <bits/stdc++.h> using namespace std; typedef long long l; // Function to find the square // difference of two large // consecutive numbers l difference(l M, l N) { return M + N; } // Driver code int main() { l M = 999999999; l N = 1000000000; cout << difference(M, N) << endl; }
Java
// Java program to find the square // difference of two large // consecutive numbers class GFG{ // Function to find the square // difference of two large // consecutive numbers static long difference(long M, long N) { return M + N; } // Driver code public static void main(String[] args) { long M = 999999999; long N = 1000000000; System.out.print(difference(M, N) +"\n"); } } // This code is contributed by 29AjayKumar
Python3
# Python3 program to find the square # difference of two large # consecutive numbers # Function to find the square # difference of two large # consecutive numbers def difference(M, N): return M + N # Driver code if __name__ == '__main__': M = 999999999 N = 1000000000 print(difference(M, N)) # This code is contributed by mohit kumar 29
C#
// C# program to find the square // difference of two large // consecutive numbers using System; public class GFG{ // Function to find the square // difference of two large // consecutive numbers static long difference(long M, long N) { return M + N; } // Driver code public static void Main(String[] args) { long M = 999999999; long N = 1000000000; Console.Write(difference(M, N) +"\n"); } } // This code is contributed by 29AjayKumar
Javascript
<script> // JavaScript program to find the square // difference of two large // consecutive numbers // Function to find the square // difference of two large // consecutive numbers function difference(M, N) { return M + N; } // Driver code let M = 999999999; let N = 1000000000; document.write(difference(M, N)); </script>
Producción:
1999999999
Publicación traducida automáticamente
Artículo escrito por divyeshrabadiya07 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA