Canna

Monday, 24 September 2018

PRIME

  • Problem Description

    "Print sum of prime numbers upto n 
    Input
    n - the number till which sum has to be done. 
    Output
    print sum of primes <=n. 
  • Test Case 1

    Input (stdin)
    5
    
    
    Expected Output
    10
  • Test Case 2

    Input (stdin)
    167
    
    
    Expected Output
    2914
  • Program
  • #include <stdio.h>
    int main()
    {
      int i, j, end, isPrime, sum=0;
    
        /* Input upper limit from user */
        scanf("%d", &end);
    
        /* Find all prime numbers between 1 to end */
        for(i=2; i<=end; i++)
        {
    
            /* Check if the current number i is Prime or not */
            isPrime = 1;
            for(j=2; j<=i/2 ;j++)
            {
                if(i%j==0)
                {
                    /* 'i' is not prime */
                    isPrime = 0;
                    break;
                }
            }
    
            /*
             * If 'i' is Prime then add to sum
             */
            if(isPrime==1)
            {
                sum += i;
            }
        }
    
        printf("%d",sum);
     return 0;
    }

No comments:

Post a Comment

Note: only a member of this blog may post a comment.