How to count the total pairs whose products exist in an array with C#

1 Answer

0 votes
using System;
using System.Collections.Generic;

internal class Program
{
	internal static int countPairsWhoseProductsExistInArray(int[] arr) {
		int total = 0, size = arr.Length;

		HashSet<int> Hash = new HashSet<int>();

		for (int i = 0; i < size; i++) {
			Hash.Add(arr[i]);
		}

		for (int i = 0; i < size; i++) {
			for (int j = i + 1; j < size; j++) {
				int product = arr[i] * arr[j];

				if (Hash.Contains(product)) {
					total++;
				}
			}
		}

		return total;
	}
	public static void Main(string[] args)
	{
		int[] arr = new int[] {2, 8, 5, 16, 6, 3, 7, 30};

		// 2 * 8 = 16
		// 2 * 3 = 6
		// 5 * 6 = 30

		Console.WriteLine("Total = " + countPairsWhoseProductsExistInArray(arr));
	}
}



/*
run:
  
Total = 3
  
*/

 



answered Jun 16, 2024 by avibootz
...