473,840 Members | 1,594 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

A little help with prime number generator, please

5 New Member
Hi!

I need some help in modifying this prime number generator code. How do I modify this code so that it assigns prime numbers to an array and returns it?
I have tried to get it work but it won't, so please help me.

Expand|Select|Wrap|Line Numbers
  1. class Prime2
  2. {
  3. int[] array = new int[25];
  4.  
  5. public int[] Primes() { 
  6.  
  7.   int i = 0;
  8.   for (i = 0; i < array.length; i++) 
  9.   {
  10.     int x, y  = 0;  
  11.     for( x = 2; x < 100; x++ )
  12.     {
  13.       if( x % 2 != 0 || x == 2 )
  14.       {
  15.         for( y = 2; y <= x / 2; y++ )
  16.         {
  17.           if( x % y == 0 )
  18.           {
  19.             break;
  20.           }   
  21.         }
  22.  
  23.         if( y > x / 2 )
  24.         {
  25.          array[i] = x;
  26.          }
  27.     }
  28. }
  29. }
  30. return array;
  31. }    
  32. public static void main (String[] args) {
  33.  
  34.     Prime2 numbers = new Prime2();
  35.     System.out.println(numbers.Primes());
  36.  
  37. }
  38.  
  39. }
  40.  
  41.  


- maks
Dec 30 '06 #1
5 3586
BSCode266
38 New Member
Hi!

I need some help in modifying this prime number generator code. How do I modify this code so that it assigns prime numbers to an array and returns it?
I have tried to get it work but it won't, so please help me.

Expand|Select|Wrap|Line Numbers
  1. class Prime2
  2. {
  3. int[] array = new int[25];
  4.  
  5. public int[] Primes() { 
  6.  
  7.   int i = 0;
  8.   for (i = 0; i < array.length; i++) 
  9.   {
  10.     int x, y  = 0;  
  11.     for( x = 2; x < 100; x++ )
  12.     {
  13.       if( x % 2 != 0 || x == 2 )
  14.       {
  15.         for( y = 2; y <= x / 2; y++ )
  16.         {
  17.           if( x % y == 0 )
  18.           {
  19.             break;
  20.           }   
  21.         }
  22.  
  23.         if( y > x / 2 )
  24.         {
  25.          array[i] = x;
  26.          }
  27.     }
  28. }
  29. }
  30. return array;
  31. }    
  32. public static void main (String[] args) {
  33.  
  34.     Prime2 numbers = new Prime2();
  35.     System.out.println(numbers.Primes());
  36.  
  37. }
  38.  
  39. }
  40.  
  41.  


- maks

Sorry about the slow reply but had to find out that hotmail wasnt accepted by thescripts.com, anyways as for your problem. Your method of making the array looks fine. However your print method is wrong, this is a mistake made by beginners such as me alot. What you will get is, if i remember it correct, the unice hash code of the object in this case the array you are trying to print. What you need to do is override the toString method in the class Object.

The toString method should look something like this:

Expand|Select|Wrap|Line Numbers
  1. public String toString()
  2. {
  3.   String s = ""; // just so your compiler will not give u problems such as the local
  4.                      // variable s may not have been initialized.
  5.    for(int i = 0; i<array.length; i++)
  6.    {
  7.     s += array[i];
  8.    }
  9.    return s;
  10. }
  11.  
Try to look in your textbook if you have one, toString methods are usually explained in those, if not try looking for something on the internet.
Once you implement this toString method you will see that you need some tweaking in the mathematical part of your code. You should also take note that methodnames usually start with lowercase letters.

~BSCode266
Jan 2 '07 #2
maks
5 New Member
Thank's! That solved my problem!

- maks
Jan 3 '07 #3
Ganon11
3,652 Recognized Expert Specialist
Expand|Select|Wrap|Line Numbers
  1. public int[] Primes() { 
  2.     int i = 0;
  3.     for (i = 0; i < array.length; i++) {
  4.         int x, y  = 0;  
  5.         for( x = 2; x < 100; x++ ) {
  6.             if( x % 2 != 0 || x == 2 ) {
  7.                 for( y = 2; y <= x / 2; y++ ) {
  8.                     if( x % y == 0 ) {
  9.                         break;
  10.                     }   
  11.                 }   
  12.  
  13.                 if( y > x / 2 ) {
  14.                     array[i] = x;
  15.                 }
  16.             }
  17.         }
  18.     }
  19.     return array;
  20. }
So far, it looks like you are going to generate the same prime number for each element in array. Your first loop is looping i from 0 to 24 to assign elements to array - which is good. But the inside of the loop is constant - that is, it doesn't depend on i (until you assign the value to the array). You should modify the inside of the loop so that it is dependent on i.
Jan 4 '07 #4
Ganon11
3,652 Recognized Expert Specialist
Also, the inside of your loop will loop through every possible prime number from 2 to 100. If that number is prime, it is assigned to a location in array. But you continue executing, even after a prime number has been found. Shouldn't you break as soon as you find a prime number, so that you aren't constantly re-assigning values to the same location?

You may want to define x outside of your initial loop. You will be generating values for each element in the array, so that outside loop is fine. Inside your first loop, instead of using a for loop, why not use a while loop to continue checking if x is prime - if x is prime, break out of the while loop, else, increment x. Once outside of the while loop, assign the ith value of array to x and end the loop.

You may want to define a function

Expand|Select|Wrap|Line Numbers
  1. private boolean isPrime(int x);
to clean up your code a bit.
Jan 4 '07 #5
Ganon11
3,652 Recognized Expert Specialist
Sorry for using three posts, but there's some error that kept me from posting the whole response as one post.
Jan 4 '07 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

9
2718
by: Greg Brunet | last post by:
In doing some testing of different but simple algorithms for getting a list of prime numbers, I ended up getting some results that seem a bit contradictory. Given the following test program (testPrimes.py) with two algorithms that both check for primes by testing only odd numbers using factors up to the square root of the value, where Primes1 is based on all of the existing primes so far, and Primes2 is based on all odd numbers, I would...
36
2702
by: Profetas | last post by:
Hi, I want to generate a random 8 bit number using rand(0 is that possible? to expecifu the base and the lenght? thanks
2
4237
by: wudoug119 | last post by:
This is my code and it will take any number that I input and say it is a prime number. Please help me... int Prime(int prime) //declares isPrime as a function using integers { int primeCount = 2; //declares primeCount as an int variable and sets it equal to 2 while(primeCount < prime) //checks if primeCount is less than prime {
4
5229
by: SweetLeftFoot | last post by:
Hello, i have designed some code that works out the first 250 prime numbers and prints them to the screen. However i need to implement 2 functions, one of which returns a 1 if the number is a prime and 0 if it isn't. I have spent ages just getting this code to work and i'm worried i need to rip it to bit to get this function to work ! The function is: int prime(int number) here is my code so far: #include...
10
4446
by: Joel Mayes | last post by:
Hi All; I'm teaching myself C, and have written a prime number generator. It is a pretty inefficient implementation of the Sieve of Eratosthenes to calculate primes up to 1,000,000. If anyone has time to critic and offer my some feedback I'd be grateful Thanks Joel
4
13280
bartonc
by: bartonc | last post by:
Description: This is a fast prime number list generator using sieve algorithm. This function return a list of prime numbers which <= argument. def primes(n): if n==2: return elif n<2: return s=range(3,n+1,2) mroot = n ** 0.5 half=(n+1)/2-1
2
2613
by: QHorizon | last post by:
Hello, I'm new to Python (I've learned everything up to iterators so far) and fairly new to Programming. This would be my first real program: #Coordinate Geometry (The whole program is not shown) import math import sys print "Welcome to the Coordinate Geometry Calculator!"
4
2328
by: cnixuser | last post by:
Hello, I am attempting to create a prime number detector that will identify all of the prime numbers within a specified range of numbers. The problem is, for some reason my program is not detecting any prime numbers and seems to be only to be printing one value of zero from the array that I am trying to store the prime numbers detected in. I believe the zero is coming from the value already stored in the array when I initialzed it, which means...
6
7003
by: sigkill9 | last post by:
I'm doing some reading in a python book and am doing one of the chapter exercises but I cant figure out how to get it to work and was hoping some of you python guru's could help out? Heres description of the problem to be solved: "A positive whole number n > 2 is prime if no number between 2 and the square root of n (inclusive) evenly divides n. Write a program that accepts a value of n as input and determines if the value is prime. If n...
0
9702
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10302
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9444
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7845
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7023
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5879
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4498
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4080
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3139
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.