# Thread: (Help) Quotient summation with prime numbers

1. Member
Join Date
Oct 2008
Posts
38
Rep Power
0
ok, now I'm pretty sure something's wrong with this loop. How can I make it include all the different prime numbers in the summation?

2. Member
Join Date
Oct 2008
Posts
38
Rep Power
0
ok, here's my code, again:
Java Code:
```/
import javax.swing.JOptionPane;

public class Project7 {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {

String input = JOptionPane.showInputDialog("Enter number");

int n = Integer.parseInt(input);
double sum = 1;

boolean isPrime = true;

for (int i=2; i<=n/2; i++) {
if (n % i ==0) {
isPrime = false;
[COLOR="royalblue"]break;
//added this from the textbook[/COLOR]
}
[COLOR="RoyalBlue"]            if(isPrime){
//changed this although it was the least important mistake[/COLOR]
sum = sum * (1+(1/(n*n)));
[COLOR="RoyalBlue"]JOptionPane.showMessageDialog(null, "The sum at this moment is:" + sum);
//added this although it kept spitting out 1.0 the only time Netbeans actually worked right[/COLOR]
}

}
JOptionPane.showMessageDialog(null, "The sum is:" + sum);

}
}```
Now, that's what I've changed, and it's not doing any of the calculations right. I just DON'T KNOW how to make all the prime numbers until n be used in the summation! Does anyone understand what I'm trying to ask??
Last edited by SapphireSpark; 10-21-2008 at 07:53 AM.

3. Lets look at this code line by line for n = 9
boolean isPrime = true; // assume number is prime
// Let n = 9
for (int i=2; i<=n/2; i++) {
if (n % i ==0) { // n=9 this is NOT true (9 % 2 =1)
isPrime = false; // even division == not prime
break;
// What is value of isPrime here for n =9 first time in loop?
}
if(isPrime){ // here isPrime is still true for 9 % 2
You need to finish the loop before testing the isPrime boolean to see if the result of the tests made in the loop determined if n was prime or not.

4. Member
Join Date
Oct 2008
Posts
38
Rep Power
0
Ok. And what about the summation part? Does the summation of all the different primes need its own loop?

5. Yes. One loop to test if a number is prime.(This would be better in a method) The other to add the found prime numbers into the summation.

6. Member
Join Date
Oct 2008
Posts
38
Rep Power
0
Is it a for loop inside the first for?

And i is the variable that becomes the prime number each time, right?

7. Can you show the code you are talking about?

8. Member
Join Date
Oct 2008
Posts
38
Rep Power
0
Nevermind, I already turned it in. When the teacher demonstrated the answer, it looks like the only thing I was missing was that second loop that added each different prime number to the product. I guess I'll try to spell out every detail next time. Thanks for the help, I guess this topic's done.

Page 2 of 2 First 12

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•