Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Jul 2012
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Trying to write a program that "factors" any number into power of primes

    I am a beginner and let's just cut to the chase.

    Here is the code I've written.


    import java.io.*;
    import java.util.Scanner;


    public class primes {

    public static void main(String[] args) {

    double x=2d, y=0d, z=0d, count=0; //z=13699293826d

    Scanner sc = new Scanner(System.in);

    System.out.print ("Enter a number: ");

    z=sc.nextFloat();

    while(x<z)
    {
    y=z%x;

    if(y==0)
    {
    System.out.println(x);
    x=1;
    z=z/x;

    }
    x++;

    }
    System.out.println (z);


    }
    }


    Here is the problem:

    1. Sometimes, a number has so many powers of 2 that the output window is filled with 2's. Is there any way to output one "2" and then the number of times it appears?

    2. Is there any better way to write a program that completes this objective? I don't mind starting from scratch.

    Thanks!
    Last edited by koudai8; 07-03-2012 at 03:46 PM.

  • #2
    New Coder
    Join Date
    Jun 2012
    Posts
    15
    Thanks
    0
    Thanked 3 Times in 3 Posts
    Well you could have a counter, so once it gets one success it won't print again. Just set the counter to 0 and in the if loop with the 'y', put

    if( y==0&&counter==0){
    counter++;
    ...}

    then it won't print out again after the counter is set to 1.

    Also you should probably just make these ints, comparing with doubles can sometimes be tricky. You may also only need to make x go to z/2 and not z. Not sure if that mathematically makes sense but i think it does, it'll just make it goes a little faster. You could use a for loop which is essentially the same thing you are doing right now


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •