Results 1 to 6 of 6
Thread: problem with sumPrime
 10272011, 03:21 PM #1Member
 Join Date
 Oct 2011
 Posts
 14
 Rep Power
 0
problem with sumPrime
This program should take an argument from the command line in the form (N integer, N prime numbers)
for example ( java sumPrime 4 150 140 13 17 )
then it should print the the prime numbers and the sum of prime numbers follows that.
in the example " output " :
13
17
30
This is the program for now... the problem is how can I add the prime numbers? and print their sum.
Java Code:package asst4; public class SumPrimes { public static void main(String[] args) { int x= Integer.parseInt(args[0]); for (int i=1; i<=x; i++) { int number = Integer.parseInt(args[i]); isPrime(number); } } public static boolean isPrime(int n) { boolean x = true; //to test if a number is prime , we check if it's divisible by integers //starting from m=2 till square root of the given number // for 0 & 1 it's known that they aren't prime numbers if ((n==1)(n==0)) { x=false; } for (int i=2; i<=Math.sqrt(n); i++ ) { if (n%i==0) { x = false; } } if (x==true ) { System.out.println(n); } return x; } public static int sumPrimes() { int sum =0; } }
Thanks in advance

Re: problem with sumPrime
The isPrime method returns a boolean value  so use it. Put it in an if expression and do something depending on the result.
 10272011, 03:58 PM #3Member
 Join Date
 Oct 2011
 Posts
 14
 Rep Power
 0
Re: problem with sumPrime
sorry but i really couldn't know how to get this right. the problem is that where should i place a for loop so that i get the sum working?

Re: problem with sumPrime
You've already got a for loop and you should use it. But first correct it since arrays go from index 0 to array length  1. So loop from i = 0 to i < array.length.
 10272011, 05:22 PM #5Member
 Join Date
 Oct 2011
 Posts
 14
 Rep Power
 0
Re: problem with sumPrime
Java Code:package asst4; public class SumPrimes { public static void main(String[] args) { int sum=0; int x= Integer.parseInt(args[0]); for (int i=1; i<=x; i++) { int number = Integer.parseInt(args[i]); isPrime(number,sum); } System.out.println(s); } public static boolean isPrime(int n,int s) { boolean x = true; //to test if a number is prime , we check if it's divisible by integers //starting from m=2 till square root of the given number // for 0 & 1 it's known that they aren't prime numbers if ((n==1)(n==0)) { x=false; } for (int i=2; i<=Math.sqrt(n); i++ ) { if (n%i==0) { x = false; } } if (x==true ) { System.out.println(n); s=s+n; } return x; } }

Re: problem with sumPrime
Again change the for loop as I recommended above.
To get a sum you must create an int variable, sum, before the loop and then add the prime to this variable inside of the loop.
Bookmarks