📌  相关文章
📜  在左右交替移动N步后的位置

📅  最后修改于: 2021-05-04 23:08:12             🧑  作者: Mango

给定三个整数N,A和B。一个人站在第0个坐标处,在第一步中将A向右移动,在第二步中B向左移动,依此类推。等等。任务是找到在N步之后他将处于哪个坐标。

例子:

方法:由于此人向右走奇数步,向左走偶数步,因此我们必须找出任一方向上步数的差。因此,获得的公式将是:

下面是上述方法的实现:

C++
// C++ program to find the last coordinate
// where it ends his journey
#include 
using namespace std;
  
// Function to return the last destination
int lastCoordinate(int n, int a, int b)
{
    return ((n + 1) / 2) * a - (n / 2) * b;
}
  
// Driver Code
int main()
{
    int n = 3, a = 5, b = 2;
    cout << lastCoordinate(n, a, b);
  
    return 0;
}


Java
// Java program to find the last coordinate
// where it ends his journey
import java.util.*;
  
class solution
{
  
// Function to return the last destination
static int lastCoordinate(int n, int a, int b)
{
    return ((n + 1) / 2) * a - (n / 2) * b;
}
  
// Driver Code
public static void main(String args[])
{
    int n = 3, a = 5, b = 2;
    System.out.println(lastCoordinate(n, a, b));
  
}
}


Python
# Python3 program to find the 
# last coordinate where it
# ends his journey 
  
# Function to return the
# last destination 
def lastCoordinate(n, a, b):
    return (((n + 1) // 2) * 
         a - (n // 2) * b)
  
# Driver Code 
n = 3
a = 5
b = 2
  
print(lastCoordinate(n, a, b))
  
# This code is contributed
# by Sanjit_Prasad


C#
// C# program to find the last coordinate 
// where it ends his journey 
using System;
  
class GFG
{
  
// Function to return the last destination 
public static int lastCoordinate(int n, 
                                 int a, int b)
{
    return ((n + 1) / 2) * a - (n / 2) * b;
}
  
// Driver Code 
public static void Main(string[] args)
{
    int n = 3, a = 5, b = 2;
    Console.WriteLine(lastCoordinate(n, a, b));
}
}
  
// This code is contributed by Shrikant13


PHP


输出:
8