Misol 1: n! faktorialni rekursiyali funksiya orqali hisoblochi dastur tuzilsin. n!=1*2*…*(n- 1)*n;
#include
int fack1(int);
int main()
{
int n;
cout << "n="; cin >> n;
cout << fack1(n) << endl;
return 0;
system ("pause");
}
int fack1(int k)
{
if (k < 0) return 0;
if (k == 0) return 1;
else return fack1(k)*fack1(k-1);
}
Misol 2: Fibonachchi ketma ketligining n – hadini rekursiya qism dastur orqali hisoblovchi dastur
#include
int fib(int);
int main()
{
int n;
cout << "n="; cin >> n;
cout << fib(n) << endl;
return 0;
}
int fib(int k)
{
if (k == 0 || k == 1) return 1;
else return fib(k - 1) + fib(k - 2);
}
n natural sonini a-darajasini aniqlovchi rekursiv funksiya tuzing
# include
using namespace std;
int daraja(int n , int a)
{
if (a == 0) return 1;
else
if (a == 1) return n;
return (a % 2 == 1) ? n * daraja(n , a-1) : daraja(n , a / 2) * daraja(n , a / 2);
}
main()
{
int n, a;
cin >> n >> a;
cout << daraja(n , a);
}
#include
using namespace std;
int funk(int n ,int a ){
if (a == 0) {
return 1 ;
}
else return n * funk(n , a-1);
}
int main()
{
// n natural son a darajasi
int a , n ;
cin >> n ; cin >> a ;
cout << funk( n , a );
return 0 ; }
Fibanochchi
//1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946
#include
using namespace std;
int fib(int number)
{
if (number < 1)
{
return 0;
}
if(number == 1){
return 1;
}
return fib(number-1) + fib(number-2);
}
int main()
{
int res = fib (8);
cout<
4. Sonni raqamlar sonini topuvchi rekursiv funksiya tuzing.
#include
using namespace std;
int t = 0;
int rekursiv(long long k)
{
k = k/10;
t++;
if(k == 0) return t;
else return rekursiv(k);
}
int main()
{
long long n;
cout<<"n=";
cin>>n;
rekursiv(n);
cout<<"Raqamlari soni "<
return 0;
}
22. Berilgan sonni necha N faktorialga tengligini aniqlovchi rekursiv funksiya tuzing.
1-usul:
#include
using namespace std;
long int faktorial(long int n, long int m, long int a, long int *p, bool *t){
if (n == 1){
m = 1;
}
else{
m = n * faktorial(n - 1, m, a, p, t);
if (a == m && !*t){
*p = n;
*t = true;
} else {
if (!*t){
*p = 0;
}
}
}
return m;
}
int main(){
int n, m;
cout << "Kiriting: "; cin >> n;
long int a = n, p;
bool t = false;
faktorial(n, m, a, &p, &t);
if (p > 0){
cout << p << "!";
} else {
cout << "Bu hech qaysi sonning faktariali emas!";
}
}
2-usul
// Faqat biror sonning faktorili bo'lganda to'g'ri natija beradi
#include
using namespace std;
int p = 0;
bool t = false;
int f(int n, int m, int a){
if (m == 1){
a = 1;
}
else {
a = 1 + f(n, m - 1, a);
if (p > a){
p /= a;
} else {
if (!t){
p = a;
t = true;
}
}
}
return a;
}
int main(){
int n, m, a = 1;
cout << "Kiriting: "; cin >> n;
m = n;
p = n;
bool b = false;
f(n, m, a);
cout << p << "!";
return 0;
}
Do'stlaringiz bilan baham: |