Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

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

1. ## 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!

• 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
•