Friday, 17 July 2015

Java Programming

Q). Retrieve the non-prime numbers within the range of a given input. Add-up the non-prime numbers and return the result.

  1. package Set1;
  2. import java.util.*;
  3. public class ClassSet45 {
  4. public static void main(String[] args) {
  5.       int i=20,j=40;
  6.       System.out.println("sum of non-prime nos. is:"+additionOfnonPrimeNos(i,j));
  7.       }
  8. public static int additionOfnonPrimeNos(int i, int j){
  9.       int k=0;
  10.       List<Integer> l1=new ArrayList<Integer>();
  11.       List<Integer> l2=new ArrayList<Integer>();
  12.       for(int a=i;a<=j;a++){
  13.             int c=0;
  14.             for(int b=2;b<a;b++)
  15.                   if(a%b==0)
  16.                         c++;
  17.             if(c==0)
  18.                   l1.add(a); }
  19.       for(int e=i;e<=j;e++)
  20.             l2.add(e);
  21.       l2.removeAll(l1);
  22.       for(int d=0;d<l2.size();d++)
  23.             k+=l2.get(d);
  24.       return k;
  25. }
  26. }