1,2,1,3,2,5,3,7,5,11,8,13,13,17,.. this serious is a mixture of 2 series all the odd term in this series from a fibonacci series and all the even term are the prime number in ascending order.find a program to find the nth term in this.
Answers
If I'm not mistaking then, this question was asked in the mock test of TCS ninja qualifier.
Well it is not that complicated. You have to take 3 loops: 1 for prime, other for fibo and the last for resulting series i.e. combining both.
Source code:
#include<stdio.h>
int main()
{ int n,flag;
int i,t=1,j;
int a,b,c,r,g;
a=0;b=1;c=0;r=1;
scanf("%d",&n);
//for fibo
if(n%2!=0)
{
while(r<=(n/2 +1))
{
g=b;
c=a;
a=b;
b=a+c;
r++;
}
printf("%d ",g);
}
else
{//for prime no
for(i=2;t<=(n/2);i++)
{
flag=0;
for(j=2;j<i;j++)
{
if(i%j==0)
{flag=1;
break;
}
}
if(flag==0)
{t++;
}
}
printf("%d ",i-1);
}
return 0;
}
#include <stdio.h>
#include <stdbool.h>
int fib(int n)
{
if (n <= 1)
return n;
return fib(n-1) + fib(n-2);
}
bool isPrime(int n) {
for(int i = 2; i < n; ++i) {
if (n % i == 0) {
//
//
//
}
}
}
int nthPrime(int n) {
int candidate=2;
int count;
for(count = 0; count < n; ++candidate) {
if (isPrime(candidate)) {
++count;
}
}
// -1;
}
int main(void) {
// your code goes here
int n;
scanf("%d",&n);
if(n%2==0)
{
printf("%d",nthPrime(n/2));
}
else
{
printf("%d",fib((n/2) +1));
}
return 0;
}