posted 6 years ago

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

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

posted 6 years ago

Hi Eido. Welcome to The Ranch!

The problem is that you aren't resetting the variables each time you go round the loop. In particular sum (the others don't matter, although there's no need to declare them where you do). So what you end up doing is calculating the sum of the factors of all the numbers up to 100.

Fix that, and it should work. If you're interested, though, that's not a very good algorithm. For a start you don't need to try dividing every number up to

The problem is that you aren't resetting the variables each time you go round the loop. In particular sum (the others don't matter, although there's no need to declare them where you do). So what you end up doing is calculating the sum of the factors of all the numbers up to 100.

Fix that, and it should work. If you're interested, though, that's not a very good algorithm. For a start you don't need to try dividing every number up to

`i`into`i`- you can stop at`sqrt(i)`. But if you want a much better way of finding all the primes up to a given number, try searching for the "Sieve of Eratosthenes".