-
Notifications
You must be signed in to change notification settings - Fork 1k
/
sterns_diatomic_series.c
57 lines (47 loc) · 1.2 KB
/
sterns_diatomic_series.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/*
C program to find the n-th element from Stern's Diatomic Series
Stern's diatomic series is the sequence which generates the integer sequence that arises
in the Calkin-Wilf tree. This sequence can be computed by the fusc function.
*/
#include <stdio.h>
int sterns_diatomic_num(int n)
{
if (n == 0)
return 0;
int dp[n + 1];
dp[0] = 0;
dp[1] = 1;
for (int i = 2; i <= n; i++)
{
if (i % 2 == 0)
dp[i] = dp[i / 2];
else
dp[i] = dp[(i - 1) / 2] + dp[(i + 1) / 2];
}
return dp[n];
}
int main()
{
int n;
printf("Enter the value of n(where you need the nth Stern's Diatomic number): ");
scanf("%d", &n);
if (n < 0)
{
printf("Invalid Value of n !!!");
return 0;
}
int res = sterns_diatomic_num(n);
printf("The %d'th Stern's Diatomic is %d", n, res);
return 0;
}
/*
Time Complexity: O(n), where 'n' is the given number
Space Complexity: O(1)
SAMPLE INPUT AND OUTPUT
SAMPLE 1
Enter the value of n(where you need the nth Stern's Diatomic number): 258
The 258'th Stern's Diatomic is 8.
SAMPLE 2
Enter the value of n(where you need the nth Stern's Diatomic number): -98
Invalid Value of n !!!
*/