Untitled
unknown
plain_text
2 years ago
1.5 kB
15
Indexable
#include <bits/stdc++.h>
using namespace std;
// Recursive algorithms
int sum_Recursive(int n){
if(n==1){
return 1;
}
else{
return n + sum_Recursive(n-1);
}
}
int combinationRecursive(int n, int k) {
if (k == 0 || k == n) {
return 1;
}
return combinationRecursive(n - 1, k - 1) + combinationRecursive(n - 1, k);
}
int gcdRecursive(int a, int b) {
if (b == 0) {
return a;
}
return gcdRecursive(b, a % b);
}
int findMin(int arr[], int left, int right) {
if (left == right) {
// If there's only one element, it is the minimal element
return arr[left];
}
int middle = (left + right) / 2;
// Recursively find the minimal elements in the two sub-series
int min1 = findMin(arr, left, middle);
int min2 = findMin(arr, middle + 1, right);
// Compare min1 and min2 to find the minimal element
return (min1 < min2) ? min1 : min2;
}
// Sum of natural numbers with non-recursive algorithms
int sum_Nonrecursive(int n){
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
return sum;
}
int main() {
int n;
cout << "Enter a positive integer n: ";
cin >> n;
cout << sum_Recursive(n) <<endl;
cout << sum_Nonrecursive(n)<<endl;
int arr[n];
cout << "Enter the elements: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int minimalElement = findMin(arr, 0, n - 1);
cout << "The minimal element in the series is: " << minimalElement << endl;
return 0;
}Editor is loading...