Go Back   CodingForums.com > :: Server side development > Java and JSP

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 07-03-2012, 01:24 PM   PM User | #1
koudai8
New to the CF scene

 
Join Date: Jul 2012
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
koudai8 is an unknown quantity at this point
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.

Quote:

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..
koudai8 is offline   Reply With Quote
Old 07-11-2012, 08:44 PM   PM User | #2
michaelh73
New Coder

 
Join Date: Jun 2012
Posts: 15
Thanks: 0
Thanked 3 Times in 3 Posts
michaelh73 is an unknown quantity at this point
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
michaelh73 is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 07:37 AM.


Advertisement
Log in to turn off these ads.