Wednesday, 20 September 2017

Sum of Two Primes : Hacker Rank Solution in C

Solution to below link problem
https://www.hackerrank.com/contests/primary-prime/challenges/is-prime-or-not-2

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int prime(long long int i)
{
            int j;
            for(j=2;j<=sqrt(i);j++)
            {
                        if(i%j == 0)
                                            return 0;
                 }
                return 1;
}

int main()
{

            long long int i,flag=0,n;
            scanf("%lld",&n);
             if(n<=4)
                    printf("%d",-1);
             else if((n-2)%2 !=0 && prime(n-2))
                    printf("%d\t%lld",2,n-2);
             else
            {
                         for(i=3;i< n-i;i=i+2)
                        {
                                    if((n-i)%2 !=0 && prime(i))
                                    {
                                                if(prime(n-i))
                                                 {
                                                            printf("%lld\t%lld",i,n-i);
                                                            flag=1;
                                                            break;
                                                }
                                    }
                        }
                        if(flag == 0)
                                printf("%d",-1);
             }  
 return 0;

}

No comments:

Post a Comment