C Online Compiler
Example: Maximum Scalar Product in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Maximum Scalar Product #include
#include
// Required for qsort // Comparison function for qsort (ascending order) int compareIntegers(const void *a, const void *b) { return (*(int*)a - *(int*)b); } // Function to calculate maximum scalar product long long maxScalarProduct(int arr1[], int arr2[], int n) { // Step 1: Sort both arrays in ascending order qsort(arr1, n, sizeof(int), compareIntegers); qsort(arr2, n, sizeof(int), compareIntegers); // Step 2: Calculate the scalar product long long product = 0; for (int i = 0; i < n; i++) { product += (long long)arr1[i] * arr2[i]; } return product; } int main() { // Step 1: Define input vectors and their size int arr1[] = {1, 2, 3}; int arr2[] = {4, 5, 6}; int n1 = sizeof(arr1) / sizeof(arr1[0]); int n2 = sizeof(arr2) / sizeof(arr2[0]); if (n1 != n2) { printf("Error: Vectors must have the same dimension.\n"); return 1; } // Step 2: Calculate and print the maximum scalar product long long result = maxScalarProduct(arr1, arr2, n1); printf("The maximum scalar product is: %lld\n", result); // Another example int arr3[] = { -1, -2, -3 }; int arr4[] = { 1, 2, 3 }; int n3 = sizeof(arr3) / sizeof(arr3[0]); result = maxScalarProduct(arr3, arr4, n3); printf("The maximum scalar product for {-1, -2, -3} and {1, 2, 3} is: %lld\n", result); return 0; }
Output
Clear
ADVERTISEMENTS