GeeCON Prague 2014*
The moose likes Beginning Java and the fly likes Find prime nums from 1-100 algorithm Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Find prime nums from 1-100 algorithm" Watch "Find prime nums from 1-100 algorithm" New topic
Author

Find prime nums from 1-100 algorithm

Eido Keva
Greenhorn

Joined: Feb 05, 2012
Posts: 1
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

Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4396
    
    8

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 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".
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Find prime nums from 1-100 algorithm