Модуль всех попарно следующих друг за другом элементов в массиве
Учитывая массив
элементы. Задача состоит в том, чтобы вывести модуль всех попарно следующих друг за другом элементов. То есть для всех пар последовательных элементов, скажем ((a [i], a [i + 1])), print (a [i]% a [i + 1]) .
Примечание : последовательные пары массива размера N (a [i], a [i + 1]) для всех i в диапазоне от 0 до N-2.
Примеры :
Ввод : arr [] = {8, 5, 4, 3, 15, 20}
Выход : 3 1 1 3 15
Ввод : arr [] = {5, 10, 15, 20}
Выход : 5 10 15Подход: решение состоит в том, чтобы пройти по массиву, вычислить и распечатать модуль каждой пары (arr [i], arr [i + 1]).
Ниже представлена реализация описанного выше подхода:
C ++
// C++ program to print the modulus// of the consecutive elements#include <iostream>using namespace std;// Function to print pairwise modulus// of consecutive elementsvoid pairwiseModulus( int arr[], int n){ for ( int i = 0; i < n - 1; i++) { // Modulus of consecutive numbers cout << (arr[i] % arr[i + 1]) << " " ; }}// Driver Codeint main(){ int arr[] = { 8, 5, 4, 3, 15, 20 }; int n = sizeof (arr) / sizeof (arr[0]); pairwiseModulus(arr, n); return 0;} |
Джава
// Java program to print the modulus// of the consecutive elementsimport java.util.*;class Geeks { // Function to print pairwise modulus// of consecutive elementsstatic 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 Codepublic 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 elementsdef pairwiseModulus(arr, n): for i in range ( 0 , n - 1 , 1 ): # Modulus of consecutive numbers print ((arr[i] % arr[i + 1 ]), end = " " ) # Driver Codeif __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 elementsusing System;class Geeks { // Function to print pairwise modulus// of consecutive elementsstatic 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 Codepublic 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
<?php//PHP program to print the modulus// of the consecutive elements// Function to print pairwise modulus// of consecutive elementsfunction pairwiseModulus( $arr , $n ){ for ( $i = 0; $i < $n - 1; $i ++) { // Modulus of consecutive numbers echo ( $arr [ $i ] % $arr [ $i + 1]), " " ; }}// Driver Code $arr = array ( 8, 5, 4, 3, 15, 20 ); $n = sizeof( $arr ) / sizeof( $arr [0]); pairwiseModulus( $arr , $n ); // This code is contributed by ajit?> |
Javascript
<script>// javascript program to prvar the modulus// of the consecutive elementsclass Geeks { // Function to prvar pairwise modulus // of consecutive elements function pairwiseModulus(arr , n) { for (i = 0; i < n - 1; i++) { // Modulus of consecutive numbers document.write((arr[i] % arr[i + 1]) + " " ); } } // Driver Code var arr = [ 8, 5, 4, 3, 15, 20 ]; var n = arr.length; pairwiseModulus(arr, n);// This code contributed by gauravrajput1</script> |
3 1 1 3 15
Сложность времени: O (n)
Вниманию читателя! Не прекращайте учиться сейчас. Освойте все важные концепции DSA с помощью самостоятельного курса DSA по доступной для студентов цене и будьте готовы к работе в отрасли. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .
Если вы хотите посещать живые занятия с отраслевыми экспертами, пожалуйста, обращайтесь к Geeks Classes Live и Geeks Classes Live USA.