Home TechnologyProgrammingJava Subscribe to RSS

Write A Java Program To Display Sum Of All Prime Number From 1 To 20?

Answer Question

1 Answer - Sort by: Date | Rating

    public Class ComputePrimeSum
    {
      int sum = 0;

      public void main (String [] args)
      {
         for (int i = 2; i <= 20; i++) // RULE OUT 1 AS WE ALREADY KNOW IT'S CASE
         {
            for (int c = 2; c <= i; c++)
            {
              if (((int) i/c == i/c) && (c < i)) // IF DIVISIBLE BY A NUMBER LOWER THAN IT
              {
                c = -1; // EXIT THE SECOND FOR LOOP
              }
              
              else if (((int) i/c == i/c) && (c == i)) // DIVISIBLE ONLY BY ITSELF
              {
                sum += i; //ADD TO THE VALUE OF SUM
              }
            }
         }
         
         System.out.printl // PRINT RESULT
      }
    }  

    I haven't tested it, so it may not work. I will test later, but the logic makes a lot of sense to me.
    0 0

    Jamesy 

    answered 7 months ago

    This stupid thing won't let me edit my answer!!! Arrghhhhhhhh
    Anyway, the last bit is:
    System.out.println(sum)
    Report
    Jamesy

    Jamesy

    commented 7 months ago

    I don't know how this works.
    Report
    Jamesy

    Jamesy

    commented 7 months ago

      More

         
         

        Ask a Question via Twitter

        Send a question to @askblurtit and we will publish it online and send you a reply everytime you receive an answer.

        Blurtit Store

        Get T-shirts, hoodies, caps and more at the Blurtit store

        Blurtit International