📜  数组中所有成对连续元素的模

📅  最后修改于: 2022-05-13 01:57:06.237000             🧑  作者: Mango

数组中所有成对连续元素的模

给定一个数组N   元素。任务是打印所有成对连续元素的模数。也就是说,对于所有连续元素对来说 ((a[i], a[i+1])), print (a[i] % a[i+1])
注意:对于从 0 到 N-2 的所有 i,大小为 N 的数组的连续对是 (a[i], a[i+1])。
例子

Input: arr[] = {8, 5, 4, 3, 15, 20}
Output: 3 1 1 3 15 

Input: arr[] = {5, 10, 15, 20}
Output: 5 10 15 

方法:解决方法是遍历数组,计算并打印每一对的模数(arr[i],arr[i+1])。
下面是上述方法的实现:

C++
// C++ program to print the modulus
// of the consecutive elements
#include 
using namespace std;
 
// Function to print pairwise modulus
// of consecutive elements
void pairwiseModulus(int arr[], int n)
{
    for (int i = 0; i < n - 1; i++) {
 
        // Modulus of consecutive numbers
        cout << (arr[i] % arr[i + 1]) << " ";
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 8, 5, 4, 3, 15, 20 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    pairwiseModulus(arr, n);
 
    return 0;
}


Java
// Java program to print the modulus
// of the consecutive elements
import java.util.*;
 
class Geeks {
     
// Function to print pairwise modulus
// of consecutive elements
static void pairwiseModulus(int arr[], int n)
{
    for (int i = 0; i < n - 1; i++) {
 
        // Modulus of consecutive numbers
        System.out.println((arr[i] % arr[i + 1]));
    }
}
 
// Driver Code
public static void main(String args[])
{
    int arr[] = { 8, 5, 4, 3, 15, 20 };
    int n = arr.length;
 
    pairwiseModulus(arr, n);
}
}
 
// This code is contributed by ankita_saini


Python3
# Python 3 program to print the modulus
# of the consecutive elements
 
# Function to print pairwise modulus
# of consecutive elements
def pairwiseModulus(arr, n):
    for i in range(0, n - 1, 1):
         
        # Modulus of consecutive numbers
        print((arr[i] % arr[i + 1]),
                         end = " ")
     
# Driver Code
if __name__ == '__main__':
    arr = [8, 5, 4, 3, 15, 20]
    n = len(arr)
    pairwiseModulus(arr, n)
 
# This code is contributed
# by Surendra_Gangwar


C#
// C# program to print the modulus
// of the consecutive elements
using System;
 
class Geeks {
     
// Function to print pairwise modulus
// of consecutive elements
static void pairwiseModulus(int[] arr, int n)
{
    for (int i = 0; i < n - 1; i++) {
 
        // Modulus of consecutive numbers
        Console.WriteLine((arr[i] % arr[i + 1]));
    }
}
 
// Driver Code
public static void Main(String []args)
{
    int[] arr = {8, 5, 4, 3, 15, 20};
    int n = arr.Length;
 
    pairwiseModulus(arr, n);
}
}
 
// This code is contributed by ankita_saini


PHP


Javascript


输出:
3 1 1 3 15

时间复杂度: O(n)
辅助空间:O(1)