Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

Members have full access to the forums. Advertisements are removed for registered users.

# Thread: Find prime nums from 1-100 algorithm

1. ## Find prime nums from 1-100 algorithm

Hi to all.
I learn java with some book and i tried to creat an algorithm that show the prime numbers form 1 to 100.
The principle beahind it was that prime numbers can be divided by themself and 1 only - so the sum of the numbers that can be divided by is - the number himself plus 1.
For example - 5 can be divided by 1 and 5 - so the sum of the dividers is 6...

So this is the algorithm i created, and its say only 3 by the println..
What is the problem please help me guys

```import java.util.Scanner;
class Primery1
{
static Scanner reader = new Scanner(System.in);
public static void main(String[] args)
{
int n, i, c ,sum =0;
for (i=2; i<=100; i++)
{
for (n=1; n<=i; n++)
{if ((i%n) == 0)
sum=n+sum;
}
c=i+1;
if (sum == c)
System.out.println(i);}

}
}```  Reply With Quote

3. ## Re: Find prime nums from 1-100 algorithm

its say only 3 by the println..
Can you show what you input to the program and what it prints out?
How often is (sum == c)?
Add a println to print out the value of c and the value of sum so you will see what the program is doing when it executes.

To copy the contents of the command prompt window:
Click on Icon in upper left corner
Select Edit
Select 'Select All' - The selection will show
Click in upper left again
Select Edit and click 'Copy'

Paste here.  Reply With Quote

4. ## Re: Find prime nums from 1-100 algorithm

```for (i=2; i<=100; i++)
{
for (n=1; n<=i; n++)
{if ((i%n) == 0)
sum=n+sum;
}
c=i+1;
if (sum == c)
System.out.println(i);}
}```

You have to restart the variable 'sum' in each for cycle because he's keeping the same sum as your previous number. In other words, the 'sum' variable is a total sum of all number's dividend from 1 to 100. You have to restart it like this:

```for (i=2; i<=100; i++)
{
sum = 0;
for (n=1; n<=i; n++)
{if ((i%n) == 0)
sum=n+sum;
}
c=i+1;
if (sum == c)
System.out.println(i);}
}```  Reply With Quote