Best way to determine if a number is evenly divisible by a double?

I need to determine if some number is divisible by some other number. A simple solution is:
public boolean isDivisibleBy(double dividend, double divisor)
   return dividend % divisor == 0;
}Unfortunately this does not work if the divisor is not an integer (e.g. 1.0 % 0.1 results in 0.1).
I am trying to find a solution with good performance, but hopefully doesn't make the code too messy. I assume someone has solved this problem before, but apparently my Google-fu is weak. :-(
Anyone have a solution they'd care to share?

Sorry, I realized my post did not ask my real question (but you answered too quick for me to edit it ;-) ).
What I'm unsure of is what metric I should use. I was hoping perhaps the maximum imprecision would be determined by the IEEE double standard. I take it from your reply this is not the case? So I should just choose whatever limit I feel will be sufficiently small for my application?
Edit: I've experimentally found 1.0E-16 to be sufficient for the imprecision in my test cases. Since the smallest imaginable divisor for my application would be several orders of magnitude larger than that, I think I will be fine just by picking an arbitrary number.
Still, I would be interested to know if the definition of the remainder function would provide any insight into the maximum imprecision which would be possible.
Anyway, thanks for the help.
Edited by: dsiegmann on Dec 11, 2007 4:18 PM

Similar Messages

  • Best way to determine insertion order of items in cache for FIFO?

    I want to implement a FIFO queue. I plan on one producer placing unprocessed Orders into a cache. Then multiple consumers will each invoke an EntryProcessor which gets the oldest unprocessed order, sets it processed=true and returns it. What's the best way to determine the oldest object based on insertion order? Should I timestamp the objects with a trigger when they're added to the cache and then index by that value? Or is there a better way? maybe something coherence automatically saves when objects are inserted? Also, it's not critical that the processing order be precisely FIFO, close is good enough.
    Also, since the consumer won't know the key value for the object it will receive, how could the consumer call something like this so it doesn't violate Constraints on Re-entrant Calls? http://wiki.tangosol.com/display/COH34UG/Constraints+on+Re-entrant+Calls
    Thanks,
    Andrew

    Ok, I think I can see where you are coming from now...
    By using a queue for each for each FIX session then you will be experiencing some latency as data is pushed around inside the cluster between the 'owning node' for the order and the location of the queue; but if this is acceptable then great. The number of hops within the cluster and hence the latency will depend on where and how you detect changes to your orders. The advantage of assiging specific orders to each queue is that this will not change should the cluster rebalance; however you should consider what happens if the node controlling a specific FIX session is lost - do you recover from FIX log? If so where is that log kept? Remember to consider what happens if your cluster splits, such that the node with the FIX session is still alive, but is separated from the rest of the cluster. In examining these failure cases you may decide that it is easier to use Coherence's in-built partitioning to assign orders to sessions father than an attribute of order object.
    snidely_whiplash wrote:
    Only changes to orders which result in a new order or replace needing to be sent cause an action by the FIX session. There are several different mechanisms you could use to detect changes to your orders and hence decide if they need to be enqueued:
    1. Use a post trigger that is fired on order insert/update and performs the filtering of changes and if necessary adds the item to the FIX queue
    2. Use a cache store that does the same as (1)
    3. Use an entry processor to perform updates to the order object (as I believe you previously mentioned) and performs logic in (1)
    4. Use a CQC on the order cache
    5. A map listener on the order cache
    The big difference between 1-3 and 4, 5 is that the CQC is i) a SPOF ii) not likely located in the same place as your order object or the queue (assuming that queue is in fact an object in another cache), iii) asynchronously fired hence introducing latency. Also note that the CQC will store your order objects locally whereas a map listener will not.
    (1) and (3) will give you access to both old and new values should that be necessary for your filtering logic.
    Note you must be careful not to make any re-entrant calls with any of 1-3. That means if you are adding something to a FIX queue object in another cache (say using an entry processor) then it should be on a different cache service.
    snidely_whiplash wrote:
    If I move to a CacheStore based setup instead of the CQC based one then any change to an order, including changes made when executions or rejects return on the FIX session will result in the store() method being called which means it will be called unnecessarily a lot. It would be nice if I could specify the CacheStore only store() certain types of changes, ie. those that would result in sending a FIX message. Anything like that possible?There is negligible overhead in Coherence calling your store() method; assuming that your code can decide if anything FIX-related needs to be done based only on the new value of the order object then this should be very fast indeed.
    snidely_whiplash wrote:
    What's a partitioned "token cache"?This is a technique I have used in the past for running services. You create a new partitioned cache into which you place 'tokens' representing a user-defined service that needs to be run. The insertion/deletion of a token in the backing map fires a backing map listener to start/stop a service +(not there are 2 causes of insert/delete in a backing map - i) a user ii) cluster repartitioning)+. In this case that service might be a fix session. If you need to designate a specific member on which a service needs to run then you could add the member id to the token object; however you must be careful that unless you write your own partitioning strategy the token will likely not live on the same cache member as the token indicates; in which case you would want a ful map listener or CQC to listen for tokens rather than a backing map listener
    I hope that's useful rather than confusing!
    Paul

  • Best method to determine the week number of a month - SQL Server 2012

    Hi,
    I'm searching the most valid and tested method to determine the week number respect to a month.
    Fe, the 1st January falls in the 1st week of January, the 1st February fall in the 1st week of February, and so on.
    I've found many solutions but I'd like to know possibly the best one.
    Thanks

    Hi Uri,
    SELECT DATEPART(week, '20150104')
         - DATEPART(week, CONVERT(CHAR(6), '20150104', 112)+'01')
         + 1
    returns 2 and not 1. It's a Sunday.
    Waiting to be spoonfed, eh?
    The one-off in my query would be very simple to figure out - I forgot to add the +1. Is too much to expect from you that you could figure it out yourself?
    And likewise, in my post I said that you should use "week" for weeks starting on Sunday, and "iso_week" if your week starts on Monday. Uri neglected to observe this, but you had the information to correct it. If you had been interested
    in doing some work yourself, that is.
    Nevertheless, there is an issue that I overlooked:
    DECLARE @day date = '20160105'
    SELECT datepart(iso_week, @day) -
           datepart(iso_week, convert(char(6), @day, 112) + '01') + 1
    This returns -51. This is because with ISO week numbering, Jan 1st falls into week 53 of the previous year, if it's on a Friday or later. Week 1 is always the week of Jan 4th. When you week this does not happen, as week 1 is always the week with Jan
    1st. (Dec 31st is always in week 53 or 54.)
    To correct for this, we need this query:
    SELECT DATEPART(iso_week, @day) -
           CASE WHEN DATEPART(iso_week, CONVERT(CHAR(6), @day, 112) + '01') < 50
                THEN DATEPART(iso_week, CONVERT(CHAR(6), @day, 112) + '01')
                ELSE 1
           END + 1
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Best way to determine if JMS server is alive in a cluster

    Can anyone give me an idea on the best way to find out if a JMS server
              in a cluster
              has failed so I can signal migration to another server in the cluster.
              Thanks Larry
              PS weblogic 7.0 sp1
              

    Hallo Larry,
              you can go via JMX and retrieve the according RuntimeMBeans in order to
              check the health state of the
              JMSServer resp. the server hosting the JMSServer. If they are not available
              or failed you can trigger the
              migration. At least that's the way I'm doing it...
              try
              JMSServerMBean jmsServer = null;
              ServerMBean candidateServer = null;
              MigratableTargetMBean migratableTarget = null;
              * Retrieve all JMSServer defined for the current domain
              Set jmsServerSet = home.getMBeansByType("JMSServer", domainName);
              Object[] jmsServers = jmsServerSet.toArray();
              * Just the first one is picked assuming there is only one defined
              * within the active FHO domain
              if(jmsServers != null && jmsServers.length > 0)
              jmsServer = (JMSServerMBean) jmsServers[0];
              if(s_logger.isDebugEnabled())
              s_logger.debug("JMSServer: " + jmsServer.getName());
              * A JMSServer can only be associated with a single target,
              * thus pick again the first from the list.
              TargetMBean[] targets = jmsServer.getTargets();
              if(targets != null && targets.length > 0)
              boolean hostingServerRunning = false;
              boolean candidateServerRunning = false;
              * Check whether the JMSServer is really associated with
              * a migratable target. Otherwise the migration must be canceled
              * since it cannot be performed!
              if(targets[0] instanceof MigratableTargetMBean)
              migratableTarget = (MigratableTargetMBean) targets[0];
              * Retrieve all available candidates and select a running instance
              * if any. First check for constrained candidate servers, than for
              * all candidate servers
              ServerMBean[] candidates =
              migratableTarget.getConstrainedCandidateServers();
              if(candidates == null || candidates.length == 0)
              candidates = migratableTarget.getAllCandidateServers();
              if(candidates != null && candidates.length > 0)
              ServerMBean hostingServer = migratableTarget.getHostingServer();
              boolean gotHostingServer = false;
              boolean gotCandidateServer = false;
              boolean runningInstance = false;
              * Loop over all candidates as long as hosting server and candidate
              * server are visited and there running state has been determined
              for(int i=0; i< candidates.length; i++)
              ServerRuntimeMBean serverRuntime = null;
              * Retrieve the current state from the according runtime MBean
              * if available
              try
              serverRuntime = (ServerRuntimeMBean) home.getMBean(new
              WebLogicObjectName(candidates.getName(), "ServerRuntime", domainName,
              candidates[i].getName()));
              runningInstance =
              serverRuntime.getState().equalsIgnoreCase(ServerRuntimeMBean.RUNNING);
              catch(InstanceNotFoundException inf)
              * When a server instance is not available, an InstanceNotFoundException will
              be raised
              * by WLS, which can be ignored
              if(hostingServer != null && hostingServer.equals(candidates[i]))
              hostingServerRunning = runningInstance;
              gotHostingServer = true;
              else
              * A running candidate server will be prefered, thus only if no running
              * instance can be detected, another instance is selected
              if(!gotCandidateServer)
              candidateServerRunning = runningInstance;
              candidateServer = candidates[i];
              gotCandidateServer = runningInstance;
              if(gotCandidateServer && gotHostingServer)
              break;
              if(s_logger.isDebugEnabled())
              s_logger.debug("Migratable Target: " + migratableTarget.getName());
              s_logger.debug("Candidate Server: " + candidateServer.getName());
              else
              throw new Exception("JMSServer not deployed on a migratable target!");
              * Retrieve the migration service coordinator for the active domain assuming
              * there exists only one and invoke the migration later on
              MigratableServiceCoordinatorRuntimeMBean coordinator = null;
              Set coordinatorSet =
              home.getMBeansByType("MigratableServiceCoordinatorRuntime", domainName);
              Object[] coordinators = coordinatorSet.toArray();
              if(coordinators.length > 0)
              coordinator = (MigratableServiceCoordinatorRuntimeMBean) coordinators[0];
              if(enforceMigrationOnInstancesDown)
              coordinator.migrate(migratableTarget, candidateServer, hostingServerRunning,
              candidateServerRunning);
              else
              coordinator.migrate(migratableTarget, candidateServer);
              s_logger.info("Migration of JMSServer from node "
              + migratableTarget.getName()
              + " to node "
              + candidateServer.getName()
              + " has been started");
              else
              throw new Exception("MigrationServiceCoordinator cannot be retrieved");
              catch(Exception e)
              s_logger.error("Could not migrate JMSServer", e);
              Regards,
              CK
              "Larry Presswood" <[email protected]> schrieb im Newsbeitrag
              news:[email protected]...
              > Can anyone give me an idea on the best way to find out if a JMS server
              > in a cluster
              > has failed so I can signal migration to another server in the cluster.
              >
              > Thanks Larry
              >
              > PS weblogic 7.0 sp1
              >

  • Advice please, best way to handle creating X number of input / edit forms

    Hi folks,
    Like the subject says, looking for a bit of advice. Let's say on page 1, we select a customer, and this customer has X number of pets (usually < 4). They click a check box for each one they want to schedule, and submit. The next page reads the collection and needs to display an input / edit form for each of the pets. What is the best way to go about making this happen?
    Thanks very much,
    -Adam vonNieda

    Why not use a tabular form and when you call the form, create how ever many rows you need for the number of pets selected?
    Thank you,
    Tony Miller
    Webster, TX

  • Pricing: Best way to determine an partial condition amount

    Hi,
    In our scenario MWST (VAT) is calculated from multiple values/conditions (price and postage&package costs).
    What is the best way to extract the VAT value for only one of these conditions? I can only think of extracting this value via ABAP within a routine however this value isn't rounded? Is there a more easy way via customizing/conditions to extract this value?
    We need this value to calculate/sum the net-value for postage and package costs.
    Kind regards,
    Tim

    What is the best way to extract the VAT value for
        only one of these conditions?
    If the requirement will not vary from billing to billing, then you can accordingly assign the From-To step number in your pricing procedure. 
    thanks
    G. Lakshmipathi

  • Best way to change IPTC phone number?

    The phone number I have in the IPTC data for pretty much all (40k+) my photos needs to be changed.
    Looking for any suggestions as to the best way to go about that. Thanks

    In Library Module, select all photos, go to Metadata tab, change your Phone#, hit enter. It will update everything.

  • Best way to determine if document is truly unsaved

    Is there a preferred method for determining whether a file is truly unsaved? I'm distinguishing between files that have have been saved and then had some changes made to them (but have a valid name and filePath) and files that have just been created during this session and have not been saved anywhere (other than a temp directory). The only thing I can think of is checking whether an error is thrown by the filePath property; is this really the best way?
    (I have looked into both the saved and modified properties, but neither provide this information I am looking for. In theory I could check the name property to see if it starts with "Untitled" but there's nothing stopping a user from actually calling a file that so I'd rather not.)
    Quick background: I have a script that lets a user browse to some files and get information about them. Files should be closed after processing, unless of course they were open to begin with. So, I do a check of each file against the documents open when the script starts running and set a flag. Just want to make sure that there isn't a better solution than catching the error.
    Brief code:
        var openDocs = app.documents.everyItem().getElements();
        for (var i = 0; i < funcDocs.length; i++)
            var funcDoc = funcDocs[i];
            var fileInUse = false;
            if (funcDoc instanceof File)
                if (openDocs.length == 0) {fileInUse = false;}
                else
                    for (var f = 0; f < openDocs.length; f++)
                        try{
                             openDocs[f].filePath;
                        }catch(e){continue;}
                        if (openDocs[f].name == funcDoc.name && openDocs[f].filePath == funcDoc.path)
                            fileInUse = true;
                            break;
                var openDoc = app.open(funcDoc, false, 1147563124);
            else
                var openDoc = funcDoc;
                fileInUse = true;
           //Do something...
            if (fileInUse == false) {openDoc.close();}
    I guess I'm looking for a bit of a sanity check that I'm not missing some more straightforward method here. Thanks in advance!

    Help>About
    Hold down CTRL or CMD and it gives a complete document history.

  • Which is the best way for posting a large number of records?

    I have around 12000 register to commit to dababase.
    Which is the best way for doing it?
    What depends on ?
    Nowadays I can't commit such a large number of register..The dabatase seems hanged!!!
    Thanks in advance

    Xavi wrote:
    Nowadays I can't commit such a large number of registerIt should be possible to insert tens of thousands of rows in a few seconds using an insert statement even with a complex query such as the all_objects view, and commit at the end.
    SQL> create table t as select * from all_objects where 0 = 1;
    Table created.
    Elapsed: 00:00:00.03
    SQL> insert into t select * from all_objects;
    32151 rows created.
    Elapsed: 00:00:09.01
    SQL> commit;
    Commit complete.
    Elapsed: 00:00:00.00
    I meant RECORDS instead of REGISTERS.Maybe that is where you are going wrong, records are for putting on turntables.

  • Best way to determine optimal font size given some text in a rectangle

    Hi Folks,
    I have a preview panel in which I am showing some text for the current selected date using a date format.
    I want to increase the size of the applied font so that it scales nicely when the panel in which it is drawn is resized.
    I want to know the best way in terms of performance to achieve the target. I did some reading about AffineTransform and determining by checking ina loop which is the correct size, but it does not feel like a good way.
    I would appreciate some tips.
    Cheers.
    Ravi

    import java.awt.*;
    import java.awt.font.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class ScaledText extends JPanel {
        String text = "Sample String";
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            Font font = g2.getFont().deriveFont(16f);
            g2.setFont(font);
            FontRenderContext frc = g2.getFontRenderContext();
            int w = getWidth();
            int h = getHeight();
            float[][] data = {
                { h/8f, w/3f, h/12f }, { h/3f, w/4f, h/8f }, { h*3/4f, w/2f, h/16f }
            for(int j = 0; j < data.length; j++) {
                float y = data[j][0];
                float width = data[j][1];
                float height = data[j][2];
                float x = (w - width)/2f;
                Rectangle2D.Float r = new Rectangle2D.Float(x, y, width, height);
                g2.setPaint(Color.red);
                g2.draw(r);
                float sw = (float)font.getStringBounds(text, frc).getWidth();
                LineMetrics lm = font.getLineMetrics(text, frc);
                float sh = lm.getAscent() + lm.getDescent();
                float xScale = r.width/sw;
                float yScale = r.height/sh;
                float scale = Math.min(xScale, yScale);
                float sx = r.x + (r.width - scale*sw)/2;
                float sy = r.y + (r.height + scale*sh)/2 - scale*lm.getDescent();
                AffineTransform at = AffineTransform.getTranslateInstance(sx, sy);
                at.scale(scale, scale);
                g2.setFont(font.deriveFont(at));
                g2.setPaint(Color.blue);
                g2.drawString(text, 0, 0);
        public static void main(String[] args) {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new ScaledText());
            f.setSize(400,400);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
    }

  • What is the best way to show/hide n number of columns ?

    Hi,
    I have a dynamic report that I have show/hide columns working using the below code. But when there are 500 or more rows it takes about a minute or more just waiting to see the columns toggle.
    What is the best way to do this?
    // Existing Javascript
    [script language="JavaScript" type="text/javascript"]
    var maxcnt= mymonths.length;
    function hideMaxEarn(){
    for(var j=0;j[maxcnt;j++){
    hideColumn('MON'+mymonths[j],'MAXCOL'+mymonths[j]);
    hideColumn('MON'+mymonths[j],'EARNCOL'+mymonths[j]);
    hideColumn('MON13','MAXCOL13');
    hideColumn('MON13','EARNCOL13');
    function showMaxEarn(){
    for(var j=0;j[maxcnt;j++){
    showColumn('MON'+mymonths[j],'MAXCOL'+mymonths[j]);
    showColumn('MON'+mymonths[j],'EARNCOL'+mymonths[j]);
    showColumn('MON13','MAXCOL13');
    showColumn('MON13','EARNCOL13');
    function getCellIndex(pRow,pCell){ 
    for(var i=0, n=pRow.cells.length;i[n;i++){ 
        if(pRow.cells[i] == pCell) return i;
    function hideColumn(pMon,pCol){
    var l_Cell = $x(pCol);
    var l_Table = html_CascadeUpTill(l_Cell,'TABLE');
    var l_Rows = l_Table.rows;
    l_CellI = getCellIndex(l_Cell.parentNode,l_Cell);
    for (var i=0, n=l_Rows.length;i[n;i++){
        if(i != 0) {
           html_HideElement(l_Rows[i].cells[l_CellI]);
    } else {
    $x(pMon).colSpan = $x(pMon).colSpan - 1;
    function showColumn(pMon,pCol){
    var l_Cell = $x(pCol);
    var l_Table = html_CascadeUpTill(l_Cell,'TABLE');
    var l_Rows = l_Table.rows;
    l_CellI = getCellIndex(l_Cell.parentNode,l_Cell);
    for (var i=0, n=l_Rows.length;i[n;i++){
        if(i != 0) {
           html_ShowElement(l_Rows[i].cells[l_CellI]);
    } else {
    $x(pMon).colSpan = 3;
    return;
    [script]

    Hi Andy,
    Yes, I replaced the code calling the same things in a loop to one loop getting the Table reference once and I build an array of column numbers at the time the report is built so I don't have to get the column number each time....
    it is a couple of seconds faster in about a 30 second response time. It will have to do it for now, no more time unless you see something in this new code...
    Thank you! Bill
    // dynamically built code
    col_nbr_array = new Array();
    col_nbr_array[0] = "1";
    col_nbr_array[1] = "2";
    col_nbr_array[2] = "4";
    col_nbr_array[3] = "5";
    col_nbr_array[4] = "7";
    col_nbr_array[5] = "8";
    col_nbr_array[6] = "10";
    col_nbr_array[7] = "11";
    col_nbr_array[8] = "13";
    col_nbr_array[9] = "14";
    col_nbr_array[10] = "16";
    col_nbr_array[11] = "17";
    col_nbr_array[12] = "19";
    col_nbr_array[13] = "20";
    col_nbr_array[14] = "22";
    col_nbr_array[15] = "23";
    col_nbr_array[16] = "25";
    col_nbr_array[17] = "26";
    col_nbr_array[18] = "28";
    col_nbr_array[19] = "29";
    col_nbr_array[20] = "31";
    col_nbr_array[21] = "32";
    col_nbr_array[22] = "34";
    col_nbr_array[23] = "35";
    col_nbr_array[24] = "37";
    col_nbr_array[25] = "38";
    col_nbr_array[26] = "40";
    col_nbr_array[27] = "41";
    // Static code
    function show_hide_column(do_show) {
    // Set Style, Show/Hide
    var stl;
    var csp;
    if (do_show){
    stl = 'block'
    csp = 3;
    }else{
    stl = 'none';     
    csp = 1;     
    // get rows object
    var l_Rows = document.getElementById('DT_RANGE').rows;
    var totCellNbr1=parseFloat(col_nbr_array[maxcnt-1])+2;
    var totCellNbr2=totCellNbr1 +1;
    var n=l_Rows.length;
    for (var i=0; i[n;i++){
        if(i != 0) { // if not the main header which spans 3 cols when expanded
          // Go through and show/hide each cell
          for(var j=0;j[maxcnt;j++){
              l_Rows[i].cells[col_nbr_array[j]].style.display = stl;
    // Totals
    l_Rows.cells[totCellNbr1].style.display=stl;
    l_Rows[i].cells[totCellNbr2].style.display=stl;
    } else { // row 1 that has Month spelled out - colspan of 3, others has max,earned and score columns for each month.
    var maxhdr = maxcnt/2;
    for(var k=1;k[=maxhdr;k=k+1){
    //alert('Header['+k+']');
    l_Rows[i].cells[k].colSpan=csp;
    // Total column
    //alert('TotHeader['+(maxhdr+1)+']');
    l_Rows[i].cells[maxhdr+1].colSpan=csp;
    [script]

  • Best way to determine what objects has been selected in a Collection?

    Hi all
    I´m currently developing an application where a user can create a PDF based on the choices made from multiple collections.
    Each collection contatins 10-50 items, and there are about 8 different collections with objects.
    Checkboxes are used to select items from these collections.
    I´m wondering how I would best determine what choices have been made, and if would be good to remove all objects from
    a collection that has NOT been chosen?
    Currently, it looks like this (exemple for one collection, but same solution is used for all collections)
    private Collection<Texture> textureList = new ArrayList<Texture>();
    private ArrayList<Texture> textureResult = new ArrayList<Texture>();
              for (Texture t : textureList) {
                   if (t.isSelected()) {
                        textureResult.add(t);
              }After this iteration, textureResult is used to create the PDF.
    This PDF contains lists with dynamic frames, so I need to now how many
    items was selected before creating the PDF.
    Wondering if this is the best/most efficient way to do this though?
    Maybe it doesn´t matter all that much with lists this small, but I´m still curios :-)
    I guess you could do something like this aswell
              while (textureList.iterator().hasNext()) {
                   Texture t = (Texture) textureList.iterator().next();
                   if (!t.isSelected()) {
                        textureList.iterator().remove();
              }Any suggetions?

    Dallastower wrote:
    I´m wondering how I would best determine what choices have been made,Are you asking how to determine which boxes have been checked? Or do you know how to do that and you're asking how to associate those boxes with items in your Collections? Or do you know how to do that and you're asking how to keep track of those selected items in the Collection?
    I don't do GUIs, so I can't help with the first two, but for the third, you could create a new collection holding just the selected ones, or remove the unselected ones from the original Collection.
    and if would be good to remove all objects from
    a collection that has NOT been chosen?That's entirely up to you. If you create the original Collection when the user makes his selection, and only need it to survive one round of selection, that may be fine. But if you need to get back to the original collection later, and it's expensive to create, then you might want to just create a second collection and add items from the original to it if they're selected.

  • Is this the best way to test a prime number?

    Ok so I think I finally got my program to work. I tested It with very big 8 digit prime numbers if that means anything. here are 2 Questions about my program"
    -Is this a way of finding prime numbers? (does the program fulfill its purpose?)
    and Second is there a smarter way of doing it?
    Here is the program:
    //This program tests if a number is a prime number
    import java.util.Scanner;
    public class Main
    public static void main ( String args [ ] )
    Scanner input = new Scanner( System.in );
    int number;
    int bob;
    System.out.print(" Enter the number you wish to test:\n");
    number = input.nextInt();
    if (number == 1)
    System.out.print(" 1 is divisible only by 1, therefore it is not prime or composite\n");
    if (number == 2)
    System.out.print(" It's Prime\n ");
    for ( int test = 2 ; test < number ; test++ )
    bob = number % test;
    if ( bob == 0)
    System.out.print("It's Composite\n");
    return;
    System.out.println("It's Prime");
    }

    I got interested in this ...
    //1. PrimeTester_BruteForce: found 3001134 primes <= 50000000 in 410500 milliseconds
    //2. PrimeTester_SieveOfEratosthenes: found 3001134 primes <= 50000000 in 4422 milliseconds
    //3. PrimeTester_SieveOfAtkin: found 3001134 primes <= 50000000 in 24843 milliseconds
    ... so Wkipedia's SieveOfAtkin algorithm apparently requires some serious optimization before it outruns the Greeks... see http://cr.yp.to/primegen.html for an optimized C implementation (which I can't follow).
    PrimeTester_BruteForce.java//find all prime numbers upto the given maximum.
    //Using the brute force method
    //http://www.newton.dep.anl.gov/newton/askasci/1995/math/MATH039.HTM
    //PrimeTester_BruteForce: found 3001134 primes <= 50000000 in 410500 milliseconds
    import java.io.PrintWriter;
    import java.io.BufferedWriter;
    import java.io.FileWriter;
    import java.io.IOException;
    public class PrimeTester_BruteForce {
         public static void main(String[] argv) throws IOException {
              long start = System.currentTimeMillis();
              PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("PrimeTester_BruteForce.txt")));
              int limit = 50000000;
              int count = 0;
    nextn:     for (int n=2; n<=limit; n++) {
                   int top = (int)Math.sqrt(n);
                   for(int i=2; i<=top; i++) {
                        if(n%i==0) {
                             continue nextn;
                   out.print(n);
                   out.print(" ");
                   if(++count%20==0) out.println();
              long took = System.currentTimeMillis()-start;
              out.println();
              out.println("PrimeTester_BruteForce: found "+count+" primes <= "+limit+" in "+took+" milliseconds");
              out.close();
    PrimeTester_SieveOfEratosthenes.java/******************************************************************************
    //find all prime numbers upto the given maximum.
    //http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
    limit = 1000000;       // arbitrary search limit
    // pressume all are prime
    for (i=2; i<=limit; i++) is_prime[i] = true;
    // eliminate multiples of each prime, starting with its square
    for (n=2; n<=sqrt(limit); n++) {
       if (is_prime[n]) {
          for (i=n^2; i<=limit; i+=n) is_prime[i] = false;
    // print the results
    for (n=2; n=<limit; n++) {
      if (is_prime[n]) print(n);
    //PrimeTester_SieveOfEratosthenes: found 164185 primes <= 1000000 in 125 milliseconds
    import java.io.PrintWriter;
    import java.io.BufferedWriter;
    import java.io.FileWriter;
    import java.io.IOException;
    public class PrimeTester_SieveOfEratosthenes {
         public static void main(String[] argv) throws IOException {
              long start = System.currentTimeMillis();
              PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("PrimeTester_SieveOfEratosthenes.txt")));
              int limit = 50000000;
              int n, i;
              boolean[] is_prime = new boolean[limit+1];
              // pressume all are prime
              is_prime[2] = true;
              for (i=2; i<=limit; i++) {
                   is_prime[i] = true;
              // eliminate multiples of each prime, starting with its square
              for (n=1; n<=Math.sqrt(limit); n++) {
                   if (is_prime[n]) {
                        for (i=n*2; i<=limit; i+=n) {
                             is_prime[i] = false;
              // print the results
              int count = 0;
              for (n=2; n<=limit; n++) {
                   if (is_prime[n]) {
                        out.print(n);
                        out.print(" ");
                        if(++count%20==0) out.println();
              long took = System.currentTimeMillis()-start;
              out.println();
              out.println("PrimeTester_SieveOfEratosthenes: found "+count+" primes <= "+limit+" in "+took+" milliseconds");
              out.close();
    PrimeTester_SieveOfAtkin.java/******************************************************************************
    //find all prime numbers upto the given maximum.
    //http://en.wikipedia.org/wiki/Sieve_of_Atkin
    limit = 1000000; // Arbitrary search limit
    array is_prime[5:limit] initial false; // Sieve array.
    biginteger x,y,n,k; // Must be able to hold 5*limit: 4x^2 + y^2!
    // put in candidate primes: integers which have an odd number of representations
    // by certain quadratic forms.
    for x:=1:sqrt(limit) do
    for y:=1:sqrt(limit) do
       n:=4x^2 + y^2; if n<=limit and n%12 = 1 or 5 then is_prime[n]:=not is_prime[n];
       n:=3x^2 + y^2; if n<=limit and n%12 = 7 then is_prime[n]:=not is_prime[n];
       n:=3x^2 - y^2; if n<=limit and x>y and n%12 = 11 then is_prime[n]:=not is_prime[n];
    next y;
    next x;
    // eliminate composites by sieving
    // if n is prime, omit all multiples of its square; this is sufficient because
    // composites which managed to get on the list cannot be square-free
    for n:=5:sqrt(limit) do
      if is_prime[n] then for k:=n^2:limit:n^2 do is_prime[k]:=false; next k;
    next n;
    // Present the results.
    print 2, 3; for n:= 5:limit do if is_prime[n] then print n; next n;
    //PrimeTester_SieveOfAtkin: found 441 primes <= 1000000 in 203 milliseconds
    import java.io.PrintWriter;
    import java.io.BufferedWriter;
    import java.io.FileWriter;
    import java.io.IOException;
    public class PrimeTester_SieveOfAtkin {
         public static void main(String[] argv) throws IOException {
              long start = System.currentTimeMillis();
              PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("PrimeTester_SieveOfAtkin.txt")));
              int limit = 50000000;
              int sqrt = (int)Math.sqrt(limit);
              boolean[] is_prime = new boolean[limit+1]; // Sieve array.
              int x, y, n, k; // Must be able to hold 5*limit: 4x^2 + y^2!
              // put in candidate primes: integers which have an odd number of representations by certain quadratic forms.
              for (x=1; x<=sqrt; x++) {
                   for (y=1; y<=sqrt; y++) {
                        //n=(4*(x^2)) + y^2; if (n<=limit && n%12 in(1,5)) is_prime[n] = !is_prime[n];
                        int xSq = (int)Math.pow(x,2);
                        int ySq = (int)Math.pow(y,2);
                        n = 4*xSq + ySq;
                        if (n<=limit && (n%12==1||n%12==5)) {
                             is_prime[n]= !is_prime[n];
                             //debug("A: x="+x+", y="+y+", is_prime["+n+"]="+is_prime[n]);
                        //n=((3*(x^2)) + y^2; if (n<=limit && n%12==7) is_prime[n] = !is_prime[n];
                        n = 3*xSq + ySq;
                        if (n<=limit && n%12==7) {
                             is_prime[n]= !is_prime[n];
                             //debug("B: x="+x+", y="+y+", is_prime["+n+"]="+is_prime[n]);
                             //debug("   if (n<=limit:"+limit+" && n%12:"+(n%12)+"==7");
                             //debug("   (3*(x^2)):"+xSq+" + (y^2):"+ySq);
                        //n=((3*(x^2)) - y^2; if (n<=limit && x>y && n%12==11) is_prime[n]= !is_prime[n];
                        n = 3*xSq - ySq;
                        if (n<=limit && x>y && (n%12==11)) {
                             is_prime[n]= !is_prime[n];
                             //debug("C: x="+x+", y="+y+", is_prime["+n+"]="+is_prime[n]);
                   }//next y
              }//next x
              // eliminate composites by sieving
              // if n is prime, omit all multiples of its square; this is sufficient because
              // composites which managed to get on the list cannot be square-free
              // for (n:=5:sqrt(limit)) {
              //   if (is_prime[n]) for (k:=n^2:limit:n^2) is_prime[k]:=false;
              for (n=5; n<=sqrt; n++) {
                   if (is_prime[n]) {
                        int nSq = (int)Math.pow(n,2);
                        for(k=nSq; k<=limit; k+=nSq) {
                             is_prime[k]=false;
                             //debug("D: n="+n+" is_prime["+k+"]="+is_prime[k]);
              // Present the results.
              int count = 2;
              out.print("2 3 ");
              for(n=5; n<=limit; n++) {
                   if(is_prime[n]) {
                        out.format("%d ", n);
                        if(++count%20==0) out.println();
              long took = System.currentTimeMillis()-start;
              out.println();
              out.println("PrimeTester_SieveOfAtkin: found "+count+" primes <= "+limit+" in "+took+" milliseconds");
              out.close();
         //private static void debug(String msg) {
         //     System.out.println(msg);
    }

  • What's the best way to determine which row a user clicked on via a link?

    Hello. Probably simple question, but my googleing is failing me. I have a table, with a column that is a command link. How can I determine which row the user clicked on? I need to take that value, and pass it to a different page to bind it for a different query. I was thinking of setting the result in a session bean? Or is there a better way?
    Thanks!

    Hi,
    You have two options:
    1. (Complex) Have your ActionListener evaluate the event to get the source, then climb the component tree up to the table and get the current row data;
    2. (Simple) Add a setPropertyActionListener to the link with value="#{var}" target="#{destination}" where var is the table's var attribute value and destination is your managed bean that required the clicked row.
    Regards,
    ~ Simon

  • What is the best way to add a large number dynamic VI's in the application builder?

    Is there a way to add all the VI's in a directory tree or library file as "Dynamic VI's" in the application builder (7.1 on Windows XP SP2)?
    Thanks,
    Mark Moss

    LabVIEW 7.1: From what I can tell, you can only add dynamic VIs one file at a time, while for support files, you can add entire folder contents.
    Have you considered uprading to LabVIEW 8.0? Things like this have been improved dramatically! You can keep all your dynamic VIs in a project folder, then add it to the build specification in one click.
    LabVIEW Champion . Do more with less code and in less time .

Maybe you are looking for

  • HT5213 update a book, problem with isbn code and paid

    if i update a paid book , the user can download free the new version as if  it were an app on the App Store ? for a minor update for bug fix i need a new isbn code or i need a new isbn code only for a major version ?

  • System log info

    Hi, In which table system log entries stored? like abap dumps =SNAP Is there any way to restrict the system log messages to some number for example to 200? I am running housekeeping job RSSNAPDEL for a period of two weeks reguraly I want to read the

  • HT5467 How to update your ios 4.3.3 (ipad 2) to ios 6

    I was always wonder how to update my ipad (ios4.3.3) to an ios 6 Please answer as soon as possible. Thank you, Ghala Bouresli

  • Re-sizing multiple images

    Can anyone help. I email my pictures to lab for printing but they need to be reduced in size (and resloution) or the download takes for ever! Is there any way I can re-size or reduce resolution on multiple images rather than doing each one individual

  • How do I replace this Dll file or delete ?

    Hi guys, Can any one tel me how to remove rpcss.dll file? The file reside at c:\windows\system32\rpcss.dll.(remote procedure call system service,I think ). Reason why I want to remove:---Its infected with virus,my AVG anti-virus is telling all the ti