📌  相关文章
📜  两个大连续数的平方差

📅  最后修改于: 2021-04-23 07:14:59             🧑  作者: Mango

给定两个正连续数字M和N,任务是找到两个数字的平方差,而无需计算这些数字的平方。
例子:

方法:这个想法是使用代数表达式来解决这个问题。问题中给出了M = N +1。因此:

  • 要计算的值为M 2 – N 2
  • 用N +1代替M时,上式变为:
(N + 1)2 - N2
  • (N +1) 2可以扩展为:
N2 + 12 + 2 * N - N2
  • 经过简化,上面的等式变为:
1 + 2 * N
1 + N + N
(1 + N) + N
M + N
  • 因此,我们只需要计算并返回M + N的值即可。

下面是上述方法的实现:

CPP
// C++ program to find the square
// difference of two large
// consecutive numbers
 
#include 
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


输出:
1999999999