### Thread: Need a little help

1. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Sep 2013
Posts
2
Rep Power
0

#### Need a little help

Hello, I wonder if you could help me fixing my java code, which's supposed count prime numbers. The code is as follws:
{ public static void main(String[] args)
{ int N = Integer.parseInt(args[0]); int count= 0;
for(int i=1; i < N; i++)
{
boolean prime = true;
if (i == 2)
count++;
else if (i % 2 == 0 && i != 2)
prime=false;
else if(i == 1)
prime=false;

for(int j=3; j*j <=N && prime == true; j+=2)//j er <=SQRT(N)
{
if (i % j == 0) prime = false;
}
if (prime == true || i == 2) count++;
}
System.out.println(count);
}
}]
It's supposed to count how many numbers of a given input are prime numbers, but I don't get the right result
2. Please edit the post and wrap the code in code tags:
[code]
>>>>>CODE HERE
[/code]

Can you explain what the code does now and what you want it to do differently.
3. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Sep 2013
Posts
2
Rep Power
0
Originally Posted by NormR
Please edit the post and wrap the code in code tags:
[code]
>>>>>CODE HERE
[/code]

Can you explain what the code does now and what you want it to do differently.
4. What did you add and where did you add it? I don't see any difference in the code in your post.

It should look like this:
Code:
private double dotProduct(double[] pointA, double[] pointB, double[] pointC)
{
double[] AB = new double[2];
double[] BC = new double[2];
AB[0] = pointB[0] - pointA[0];
AB[1] = pointB[1] - pointA[1];
BC[0] = pointC[0] - pointB[0];
BC[1] = pointC[1] - pointB[1];
double dot = AB[0] * BC[0] + AB[1] * BC[1];

return dot;
}
I don't get the right result
Please explain. Show current result and desired output.
Last edited by NormR; September 16th, 2013 at 03:59 PM.
5. Here is the working code. It had to be modified a lot, I suppose. But, your base code was still used so that you can follow along:

Code:
{
public static void main(String[] args)
{
if(args.length == 0)
{
System.out.println("Please provide a numeric input argument.");
System.exit(0);
}
int N = Integer.parseInt(args[0]);
int count= 0;
boolean prime;

System.out.println("Now printing prime numbers between 0 and " + N);
if(N > 1)
{
System.out.print("2, ");  // 2 will always be prime.
count++;
}
for(int i=3; i < N; i+=2) // Only check odd numbers
{
prime = true; // Success flag
for(int j=3; j <= N ; j++)
{
if (i % j == 0 &&  i != j)
{ // Number is divisible by other than 1 or itself
prime = false; // This is not prime; so, no need to check any more
// for this 'i' number.
break; // break out of inner for loop
}
} // end inner for loop
if(prime == true)
{
System.out.print(i + ", ");
count++;
}
} // end outer for loop
System.out.println("\n" + count + " primes found.");
} // end main()
} // end class
Here is the output:

Code: