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
Code :
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);}
}
}
Re: Find prime nums from 1-100 algorithm
Quote:
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.
Re: Find prime nums from 1-100 algorithm
Code :
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:
Code :
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);}
}