podaj specyfikację i zapisz w c++ program wyznaczający n-ty wyraz ciągu liczbowego postaci: 0, 1, -1, 2, -2, 3, -3, 4, -4. Zapisz dwie funkcje: rekurencyjną i iteracyjną
Napisz program, który wyznacza n-ty wyraz ciągu liczbowego o postaci: 0, 1, -1, 2, -2, 3, -3, 4, -4, ...
Program powinien składać się z dwóch funkcji: rekurencyjnej i iteracyjnej.
Sygnatura funkcji rekurencyjnej:
int sequenceRec(int n);
Opis: Funkcja przyjmuje na wejściu n - liczbę naturalną określającą numer szukanego wyrazu ciągu. Funkcja rekurencyjnie oblicza i zwraca n-ty wyraz ciągu.
Sygnatura funkcji iteracyjnej:
int sequenceIter(int n);
Opis: Funkcja przyjmuje na wejściu n - liczbę naturalną określającą numer szukanego wyrazu ciągu. Funkcja iteracyjnie oblicza i zwraca n-ty wyraz ciągu.
Odpowiedź:
Napisz program, który wyznacza n-ty wyraz ciągu liczbowego o postaci: 0, 1, -1, 2, -2, 3, -3, 4, -4, ...
Program powinien składać się z dwóch funkcji: rekurencyjnej i iteracyjnej.
Sygnatura funkcji rekurencyjnej:
int sequenceRec(int n);
Opis: Funkcja przyjmuje na wejściu n - liczbę naturalną określającą numer szukanego wyrazu ciągu. Funkcja rekurencyjnie oblicza i zwraca n-ty wyraz ciągu.
Sygnatura funkcji iteracyjnej:
int sequenceIter(int n);
Opis: Funkcja przyjmuje na wejściu n - liczbę naturalną określającą numer szukanego wyrazu ciągu. Funkcja iteracyjnie oblicza i zwraca n-ty wyraz ciągu.
Przykłady użycia:
sequenceRec(5) zwróci wartość 2
sequenceIter(7) zwróci wartość -3
kod C++:
#include <iostream>
using namespace std;
// funkcja rekurencyjna
int sequenceRec(int n) {
if (n == 0) {
return 0;
} else if (n % 2 == 0) {
return -sequenceRec(n/2);
} else {
return n/2 + 1;
}
}
// funkcja iteracyjna
int sequenceIter(int n) {
int result = 0;
for (int i = 1; i <= n; i++) {
if (i % 2 == 0) {
result -= sequenceRec(i/2);
} else {
result += i/2 + 1;
}
}
return result;
}
// przykłady użycia
int main() {
cout << sequenceRec(5) << endl; // wyświetli 2
cout << sequenceIter(7) << endl; // wyświetli -3
return 0;
}