Can you write this program more efficiently?

Hello :)
I am trying to write a program that does the following:
"The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 317584931803?"
Since we are dealing with such a huge number, I've used the BigInteger class to handle it. But the problem is, the following code is inefficient..... I mean, its been calculating for the past 2.5 hours ;( I its still only on the 8th digit. I was wondering if someone could write this more efficiently?
import java.math.*;
public class euler6 {
     public static void main (String arhs[]){
           BigInteger a[]=new BigInteger[999];
           int j=0;
           BigInteger bi = new BigInteger("317584931803"); //*********
           BigInteger i=new BigInteger("2");
           final BigInteger one=new BigInteger("1");     
           final BigInteger zero=new BigInteger("0");     
           boolean state     ;
     for(;i.compareTo(bi)==-1;i=i.add(one))
          { //System.out.println(i);
            //System.out.println(bi.mod(i)+"*");
            //System.out.println(bi.mod(i).equals(zero)+"**");
               if ((bi.mod(i).equals(zero))&& (findPrime(i)))
                    {a[j]=i;
                     j++;}
     for(int f=0;f<a.length;f++)
          System.out.print(a[f]+" ");
     public static boolean findPrime(BigInteger n){
               final BigInteger one=new BigInteger("1");
               final BigInteger zero=new BigInteger("0");
               BigInteger x=new BigInteger("2");
               for(;n.divide(x).compareTo(one)==1;x=x.add(one))
                    if (n.mod(x).equals(zero))          
                         return false;
                    return true;

Hi,
I agree with prev poster, you don't have to use BigInteger since long is sufficient.
Try this, more optimized than initial version, yet still using brute force ... The drawback is, if the given number 317584931803 is a prime number .. then ... it will also take 24 hours to compute ... can't help that.
My idea is, let's say I have number 30.
So, I will search all possibility between 2 to 15. My reason is the factor will not exceed from 30 div 2 which is 15.
While doing brute, I will decrease the iteration boundary.
Eg:
- 30 is succesfully devided by 2, then iteration will stop bruting force up to iteration #15.
- next iteration, 30 is succesfully devided by 3, then iteration will stop bruting force up to iteration #10.
- next iteration, 30 is succesfully devided by 5, then iteration will stop bruting force up to iteration #6.
So, total there is only 4 iterations to check the factor of 30. And I get these number: 2, 15, 3, 10, 5, 6
The next step would be checking which of the numbers are prime, and we get 2, 3, and 5.
My algorithm is something like this:
import java.util.*;
public class PF // stands from Prime Factors ..
public static void main(String s[]) throws Exception {
        long num = 317584931803l;
        List factors = new ArrayList(255);
        long div2 = (long) (num / 2);
        for (int i=2; i<=div2; i++) {
                if (num % i == 0) {
                        div2 = (int) (num / i);
                        factors.add(new Long(i));
                        factors.add(new Long(div2));
                Thread.yield();
        Iterator iter = factors.iterator();
        while (iter.hasNext()) {
                long factor =  ((Long) iter.next()).longValue();
                if (isPrime(factor)) {
                        System.out.println(factor);
static boolean isPrime(long num) throws Exception {
        long div2 = (long) (num / 2);
        for (int i=2; i<div2; i++)  {
                if (num % i == 0) return false;
                Thread.yield();
        return true;
}The reason I put Thread.yield() is so it won't hang your machine ... this happens if the big number you test is a prime number...
My machine (Intel pentium III 700 MHz, 512 MB SDRAM) takes less than 1 second to compute ... ;-)
Alex

Similar Messages

  • I have Photoshop CS4,on how many computers can you install this program ?

    Hello,
    I got Photoshop CS4. On how many computers can you install this program ?
    Sonste

    The license and activation rights are for a single user on two computers that are not used simultaneously—such as your desktop machine and your laptop.

  • Can Anyone Write a Program that does this?

    Once again , I know it's simple but I unfortunatly can't accomplish this task if anyone can write this program for me with the use of simple recursive arguements I would appreciate it..
    pre: n greater than or equal to 0
    post: return true if n is prime and false otherwise
    thats the problem

    I scrapped working on that one , heres what im doing now..public class plus251
    We are to Recursively add well you can read the pre and post conditions, now im basically supposed to follow this same setup which I wrote out , but now im too multiply by adding and I cant figure out the recursive part I know that the base case is if a == 1 return b , but its the else which I have no clue how to write..
    public static void main(String[]args)
         /* pre: a and b are positive integers
         post: outputs a + b by adding 1 to b, a times
         int a, b;
         System.out.println("enter an integer");
    a = Console.readInt();
    System.out.println("enter an integer");
    b = Console.readInt();
         System.out.println("a+b = "+ plus(a,b));
    public static int plus(int a, int b)
         /* pre: a and b are positive ints
         post: returns a + b
         if (a==0)
         return(b); /* this will add the accumulated
    ones to b to get the total */
         else
         return(1+plus(a-1, b)); /*this returns 1 until a
    becomes 0 */
         a is 0 ---- return b
         plus(b, k) ---- returns mathplus(b, k)
         plus(b, k+1) --- returns mathplus(b, k+1)
    plus(b,k+1) ---- returns 1+ plus(b, k)
    |
         |          1+ mathplus(b, k)
    |
         ------------------ mathplus(b, k+1)

  • Hello.I can`t buy applications in my apple id.Then i buy in applications writes error contact support.Can you fix this problem?Thaks

    Hello.I can`t buy applications in my apple id.Then i buy in applications writes error contact support.Can you fix this problem?Thaks

    We are all itunes users just like you.
    You need to contact itunes support.
    http://www.apple.com/support/itunes/contact/

  • I bought Photoshop CS6 Extended(education edition) for Mac. Now ik want to install it on my (new) macbook. I have the product code and serial number. I receive an error code: may be a false copy. How can I install this program?

    In 2012, I bought Photoshop CS6 Extended (education edition) for Mac. Now I want to install it on my new Macbook. I have the correct serial number and product code, but I receive an error message: the software may be a false copy etc....What to do?

    Here is a copy of the error
    This means : Installation failed.
    Verification of the Adobe Software failed
    The product you want to install is no valid Adobe product and seems to be falsified.
    HUgo
    Op 29-aug.-2014, om 23:42 heeft Jeff A Wright <[email protected]> het volgende geschreven:
    I bought Photoshop CS6 Extended(education edition) for Mac. Now ik want to install it on my (new) macbook. I have the product code and serial number. I receive an error code: may be a false copy. How can I install this program?
    created by Jeff A Wright in Downloading, Installing, Setting Up - View the full discussion
    Hugo please turn off your e-mail signature.
    If your serial number is listed as being valid at http://www.adobe.com/ then I would recommend obtaining a fresh copy of the installation files.  You can find details on how to locate your serial number at Find your serial number quickly - http://helpx.adobe.com/x-productkb/global/find-serial-number.html.
    To download a fresh copy of the installation files please see Download CS6 products.
    Please note that the Adobe Forums do not accept email attachments. If you want to embed a screen image in your message please visit the thread in the forum to embed the image at https://forums.adobe.com/message/6685617#6685617
    Replies to this message go to everyone subscribed to this thread, not directly to the person who posted the message. To post a reply, either reply to this email or visit the message page:
    To unsubscribe from this thread, please visit the message page at . In the Actions box on the right, click the Stop Email Notifications link.
    Start a new discussion in Downloading, Installing, Setting Up by email or at Adobe Community
    For more information about maintaining your forum email notifications please go to http://forums.adobe.com/thread/416458?tstart=0.

  • I have a problem with adobe support advisor, how can i reinstall this program

    i have a problem with adobe support advisor, how can i reinstall this program

    hi wie kann ich adobe support advisor reinstalieren mac , ich bekomme fehlermeldung beim photoshop installation
    Von meinem iPhone gesendet
    Am 17.08.2014 um 07:17 schrieb Willi Adelberger <[email protected]>:
    i have a problem with adobe support advisor, how can i reinstall this program
    created by Willi Adelberger in Deutsche Foren - View the full discussion
    Kannst Du mal anfangen Deine Frage zu stellen?
    Please note that the Adobe Forums do not accept email attachments. If you want to embed a screen image in your message please visit the thread in the forum to embed the image at https://forums.adobe.com/message/6647388#6647388
    Replies to this message go to everyone subscribed to this thread, not directly to the person who posted the message. To post a reply, either reply to this email or visit the message page:
    To unsubscribe from this thread, please visit the message page at . In the Actions box on the right, click the Stop Email Notifications link.
    Start a new discussion in Deutsche Foren by email or at Adobe Community
    For more information about maintaining your forum email notifications please go to http://forums.adobe.com/thread/416458?tstart=0.

  • How can i write this C-Code in G-Code

    hallo
    how can I write this C-Code in LabVIew ,
    for a=0; a=<10; a++
       for b=0; b=5 ; b+2
            X= 3+b;
      Y=1+a;
    please see the attachment and tell me where is the problem
    Attachments:
    Unbenannt 11.vi ‏43 KB

    Well, at least you tried and got some of it right.
    I think this should do what you want, but my C is rusty. Is the increment performed before or after the loop executes? If it's after, then I believe the loop should iterate 11 times, not 10.
    In any case, you should note that for a literal translation, you would need to add a sequence structure to guarantee that Y was written to only after the inner loop finished because of the way data-flow works.. Also, note that controls and indicators in LabVIEW are not equivalent to variables. They can be used as such, but they usually should not be.
    Another point about this is that you probably want to use the correct data type - the orange terminals are floating point indicators (of double precision, in this case) and you want integers.
    To learn more about LabVIEW, I suggest you try looking at some of these tutorials.
    Try to take over the world!
    Attachments:
    C.png ‏4 KB

  • Can you write vertically in the cell of a table, can you write vertically in the cell of a table

    can you write vertically in the cell of a table, can you write vertical

    If you don't understand that my response was a smiling echo of the stammering question I really can't help you.
    I guess that my 36725 points prove that I may be helpful. It seems that at this time you don't really know what are helpful answers.
    Using spreadsheets since more than twenty years, I know that storing something in an auxiliary object floating upon a cell isn't a serious workaround to the asked question. We may be sure that more or less soon, the object will no longer be were it was supposed to be.
    At this time, if we want to put a vertical text in a cell it's safer to insert a character, a linefeed, a character, a linefeed … which, one more time is echoing the stammering question.
    Yvan KOENIG (VALLAURIS, France) vendredi 29 avril 2011 14:37:08
    Please :
    Search for questions similar to your own before submitting them to the community

  • Can someone execute this program?

    Can someone execute this program for me and tell me if it works correctly? My DOS is acting funny.
    look for these things:
    - accepts input from keyboard and places them into an array
    - continues to accept names until a blank name is entered
    - array can contain up to 15 names
    - after all names are entered, it displays the contents of the array
    and writes them to a file
    - output should be in 2 columns
    if you see a problem, please tell me how to fix it.
    import java.io.*;
    * the purpose of this program is to read data from the keyboard
    * and put it into a sequential file for processing by ReadFile
    * @author Maya Crawford
    public class Lab0
    * this function will prompt and receive data from the keyboard
    * @return String containing the data read from the keyboard
    * @param BufferedReader that is connected to System.in
    */ (keyboard)
    public static String getData(BufferedReader infile)
    throws IOException
    System.out.println("enter a name");
    return infile.readLine();
    * this is the main program which will read from the keyboard and
    * display the given input onto the screen and also write the data
    * to a file
    * @param Array of Strings (not used in this program)
    public static void main(String[] args)
    throws IOException
    int i;
    String[] outString = new String[16];
    DataOutputStream output=null;
    // this code assigns the standard input to a datastream
    BufferedReader input= new BufferedReader(new InputStreamReader(System.in));
    // this code opens the output file...
    try
    output= new DataOutputStream(new FileOutputStream("javaapp.dat"));
    // handle any open errors
    catch (IOException e)
    System.err.println("Error in opening output file\n"
    + e.toString());
    System.exit(1);
    // priming read......
    for(i=0;i<outString.length;i++)
    outString=getData(input);
    // this is the loop to continue while nnonblank data is entered
    while (!outString.equals(""))
    for(i=0;i<outString.length;i++)
    outString[i]=getData(input);
    outString[i] = input.readLine();
    System.out.println("Name entered was:"+ outString[i]);
    output.writeBytes(outString[i]+"\r\n");
    int rcol=(outString.length+1)/2;
    for(i=0;i<(outString.length)/2;i++)
    System.out.println(outString[i]+"\t"+outString[rcol++]);
    // flush buffers and close file...
    try
    output.flush();
    output.close();
    catch (IOException e)
    System.err.println("Error in closing output file\n"
    + e.toString());
    // say goodnight Gracie...
    System.out.println("all done");

    Ok, here is what I came up with. I commented most of what I changed and gave a reason for changing it. My changes aren't perfect and it still needs to be tweeked. When you run the program you have to hit the enter key every time once before you type a name. When you are done typing names hit the enter key twice and it will output the names entered into the array. Like I said, it isn't perfect, and that part you will need to fix.
    import java.io.*;
    * the purpose of this program is to read data from the keyboard
    * and put it into a sequential file for processing by ReadFile
    * @author Maya Crawford
    public class Lab0
         * this function will prompt and receive data from the keyboard
         * @return String containing the data read from the keyboard
         * @param BufferedReader that is connected to System.in
         */ //(keyboard)
         //On the above line where you have (keyboard), it wasn't commented out in your
         //program and it was throwing a error.
         public static String getData(BufferedReader infile)
         throws IOException
              System.out.println("enter a name");
              return infile.readLine();
         * this is the main program which will read from the keyboard and
         * display the given input onto the screen and also write the data
         * to a file
         * @param Array of Strings (not used in this program)
         public static void main(String[] args)
         throws IOException
              int i;
              String testString; // Created to hold the string entered by the user, because your
                                 // outString array wasn't working for that.
              String[] outString = new String[16];
              DataOutputStream output=null;
              // this code assigns the standard input to a datastream
              BufferedReader input= new BufferedReader(new InputStreamReader(System.in));
              // this code opens the output file...
              try
                   output= new DataOutputStream(new FileOutputStream("javaapp.dat"));
              // handle any open errors
              catch (IOException e)
                   System.err.println("Error in opening output file\n"
                   + e.toString());
                   System.exit(1);
              // priming read......
              testString = " ";  // Initialize testString
              int placeMark = 0; // to input the String entered by the user into the outString
                                 // array, it needs to know which position to enter it into.
              while (!testString.equals(""))
                   testString=getData(input);
                   testString = input.readLine();
                   System.out.println("Name entered was:"+ testString);
                   // Put the testString into the outString[] array.
                   // A lot of the time when you used outString you forgot to use the [x] to indicate
                   // which position you wanted to access.
                   outString[placeMark] = testString;
                   output.writeBytes(testString+"\r\n");
                   placeMark++;
            // Created a do/while loop to display the list of outString.
              int nextEntry = 0;
              do
                   System.out.println(outString[nextEntry]);
                   nextEntry++;
              }while(!outString[nextEntry].equals(""));
              // flush buffers and close file...
              try
                   output.flush();
                   output.close();
              catch (IOException e)
                   System.err.println("Error in closing output file\n"
                   + e.toString());
              // say goodnight Gracie...
              System.out.println("all done");
    }

  • The past few days every time I open firefox I get the windows' "do you want this program to make changes to your computer..."

    Hello
    I would be so grateful to know how to fix t his, because it's really getting on my nerves.
    I have windows 7 pro 64 bit. I mostly always use firefox. Whenever i opened a new browser, I never got hit with the windows badge and "Do you want this program to make changes to your computer...." or something to that effect. YOu who have windows 7 know what I mean. Of course I click yes, but I NEVER had to do this before. I don't know what changed, what might have happened. I had to have help with some software unrelated to firefox and someone had remote work on my notebook, but he should not have changed browser settings. It is really irritating me to now end to always open the browser now and have to hear that annoying thing and the badge.
    My other browsers IE and chrome do not do this.
    How can I fix this? It was never the case before for years.
    thanks I am grateful in advance. I can't use this browser if this s going to happen it gets on my nerves.

    You're welcome.

  • Crystal Report XI: Can you write your query in SQL instead of using the GUI

    Hello
      In crystal report version XI, can you write your query in sqlplus and then use the crystal report designer to build your report instead of using the GUI . I would like to be able to go database and show sql query and open that query and make changes directly there, is that possible on this version, if yes is there a setting somewhere? Please let me know.
    Thank you
    alpha

    Moved to Database forum.
    No you can no longer modify the SQL directly. Use a Command Object to enter the SQL directly.
    Thank you
    Don

  • Is there anyone there? I hope there is someone who can you understand this problem and have the common sense to respond?  I open gmail. I want to save an email to one of my folders. I position my cursor over the appropriate Folder icon or by choice, to th

    Is there anyone there? I hope there is someone who can you understand this problem and have the common sense to respond?
    I open gmail. I want to save an email to one of my folders.
    I position my cursor over the appropriate Folder icon or by choice, to the Trash.
    The friendly finger pointing cursor icon changes to an arrow icon.
    The hand icon allows me flawless access to opening and/or moving emails.
    The arrow, however does not open the link.
    On the Google menu bar the cursor hand with finger opens the links to Everett (my name), Search, Images, Maps and Play.
    When I attempt to open the remaining links in the menu bar (YouTube, News, Gmail, Drive, Calendar and More) the arrow icon replaces the hand. The arrow icon does not work. It will not activate these links.  Nor does it open email messages in the Inbox.
    Usually I reset, even reboot Safire and sometimes the problem goes away, then reappears.
    Can you imagine if this condition should it happen to a tech savvy Google Support person? Perhaps one can share and make my problem go away.
    I am considering dropping Google as my mail source. Unfortunate!
    Everett Halvorsen
    [email protected]
    718.490.3824

    I have uninstalled my Access Connection, but this problem seems to persist. IBM technician have changed the wireless card of my T60, the first few days after it was changed was very fine, no problem at all. About a week later, the problem occured again, and it happened quite frequently after that occurence. Now i really have no idea what is the cause and how to solve it. Will be greatful if there is anyone that can help me.

  • Can you install a program...

    Can you install a program, like the sims 2, to an external hard drive?
    Sorry is this has been asked a million times
    iMac G5 (without iSight)   Mac OS X (10.3.9)   Goldfrapp Fan

    Hello,
    Yes, if your internal hard drive's space is limited / low, then installing on an external hard drive is a perfectly fine option.
    Keep AxL's comments in mind.
    And, also consider that it will probably run a little slower from the external drive. To keep performance up, you should at least use a FireWire 400 drive and get one that spins at 7200 R.P.M.
    If you use a USB 2.0 drive, you will definitely be complaining about performance while using the program.
    And, most updaters are available for download, and usually ask you which drive / program location to install them to. So, that probably won't be a problem. It's a consideration. But, probably not a huge issue.
    I hope this helps.
    Let us know if you have other questions.
    P.S., if you'd like, go ahead and click the "Helpful" or "Solved" buttons on any of the posts / replies above if you feel they were helpful or adequately answered your question.

  • How can I get this program to work -- Adobe Send or Adobe SendNow

    How can I get this program to work?  I have used Adobe SendNow successfully for several years and am on automatic renewal and getting nothing but frustration for my money!  I have been unsuccessful at sending anything in the past several months.  Today while working on a deadline and many unsuccessful attempts to upload files, I signed up for a free trial at a competitor in order to get my files sent.  Want a refund  -- or better yet, keep my money and get it to work right again.

    You can't.
    Sounds like it he gave you a stolen iPhone or at least a worthless one.

  • List v = new Vector() how can i write this ?

    List v = new Vector() how can i write this ?
    vector does not 'extends' List rather it 'implements' only ......so how can write this way ? ( polymorphism applies only for 'extends' ).

    my question in a simple way is :
    List some_list extends Vector
    No, List is an interface; Vector is a concrete class. Read the javadocs.
    Vector implements List
    >
    AND
    List some_list implements Vector
    are these two same in behaviour
    our  apart from theoretical differences ?thanks
    Interfaces don't have any implementation; they're pure method signatures. When a concrete class implements an interface, it makes a promise that says "I will provide implementations for exactly these methods. Any client can call a method from the interface and I will do something 'sensible' if I'm written correctly."
    From the point of view of static and dynamic types, there's no difference between interfaces and classes.
    C++ has interfaces, too - they're classes with all pure virtual methods. If you understand how C++ works, the concept shouldn't be hard.
    ArrayList is preferred precisely because it isn't synchronized by default. (You can always make it so using java.util.Collections if you wish later on.) If you don't need synchronization, why pay the performance penalty?

Maybe you are looking for

  • [SOLVED] database file for multilib does not exist

    Hey guys I ran into a problem today when I tried to install the proper packages I needed to use my wifi card. However when I tried to install it it gives me the error "database file for multilib does not exist" I can t seem to find out why I even tri

  • How do I move movies to an external drive?

    I have an external drive and would like to move all of my IMovie projects and event library to it and continue to only use my external drive for them. I am not sure how to do that, Could some one help please? I thank you in advance

  • Convert.To​Byte and logical masks, from VB to LabVIEW

    Hi guys, I have to write a VI communicating via RS232 with a microcontroller for a PWM application. A colleague has given me the GUI he has developpd in VB and I would like to integrate it into my LabVIEW programme by converting the VB code into Labv

  • Free version installation wont work

    I am stuck on this Adobe Download Assistant page where I am asked to log in, I have but nothing happens when I click 'Sign in'.

  • Do i need to drop index even when i drop data in data target

    Hi ,    I am having a PC and i am dropping entire data in my data target. do i still need to add drop index to my process chain. Can any one tell me what extactly happens if i drop data in a data targets and what happend if i drop the index? which ta