find sum of prime numbers from 1 to 100 in java code example

Example 1: sum of prime numbers in a digit in java

import java.util.*;
public class PrimeDigit
{
    public boolean IsPrime(int i)
    {
        boolean b=true;
        int d=2;
        while(d<i/2)
        {
            if (i%d==0)
            {
                b=false;
                break;
            }
            d++;
        }
        return b;
    }
    public static void main(String []args)
    {
       Scanner sc=new Scanner(System.in);
       System.out.print("Enter A Number : ");
       int i=sc.nextInt();
       int s=0,r;
       PrimeDigit pd=new PrimeDigit();
       while(i>0)
       {
            r=i%10;
            if(pd.IsPrime(r))
			{
                s = s + r;
			}
            i = i / 10;
       }
       System.out.print("Sum Of The Prime Digits : " + s );
    }
}

Example 2: primenumbers java

It will display the prime numbers between 1 and 100.

class PrimeNumbers
{
   public static void main (String[] args)
   {		
       int i =0;
       int num =0;
       //Empty String
       String  primeNumbers = "";

       for (i = 1; i <= 100; i++)         
       { 		  	  
          int counter=0; 	  
          for(num =i; num>=1; num--)
	  {
             if(i%num==0)
	     {
 		counter = counter + 1;
	     }
	  }
	  if (counter ==2)
	  {
	     //Appended the Prime number to the String
	     primeNumbers = primeNumbers + i + " ";
	  }	
       }	
       System.out.println("Prime numbers from 1 to 100 are :");
       System.out.println(primeNumbers);
   }
}

Tags:

Misc Example