Guest User

Untitled

a guest
Oct 19th, 2017
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.08 KB | None | 0 0
  1. public class Factors {
  2. private int start = 1, end;
  3.  
  4. public static void main(String[] args) {
  5. Factors findfactors = new Factors();
  6.  
  7. findfactors.getRange();
  8. findfactors.listPrimeFactorizations();
  9. }
  10.  
  11. // Prompt the user for input. Save the input with the
  12. // appropriate variables.
  13. public void getRange() {
  14. // start = Starting number 1
  15. start = Prompt.getValue("Enter a starting integer from 2 to 100 -> ");
  16.  
  17. while (start > 100 || start < 2) {
  18. start = Prompt.getValue("Please enter a valid starting integer from 2 to 100 -> ");
  19. }
  20.  
  21. // end = Starting number 2
  22. end = Prompt.getValue("Enter an ending integer from " + start + " to 999 -> ");
  23. while (end < start || end > 999) {
  24. end = Prompt.getValue("Please enter a valid ending integer from " + start + " to 999 -> ");
  25. }
  26. }
  27.  
  28. /**
  29. * List the integers, from start to end. Show the prime factorization for
  30. * each integer in the list. Call printFactorization for each integer in the
  31. * list.
  32. */
  33. public void listPrimeFactorizations() {
  34.  
  35. for (; start <= end; start++) {
  36. // This loop checks for the amount of numbers left to factor
  37. printFactorization(start);
  38. }
  39.  
  40. }
  41.  
  42. // Print the prime factorization for the positive
  43. // integer passed in the parameter list.
  44. public void printFactorization(int num) {
  45.  
  46. boolean firstTime = true; // true if 1st print
  47.  
  48. int i = num;
  49. int base = 2;
  50.  
  51. System.out.print(num + " = ");
  52.  
  53. while (base <= num) {
  54.  
  55. // check if divisible by the base with no remainder
  56. while (i % base == 0) {
  57. i = i / base;
  58.  
  59. if (firstTime == false) {
  60. System.out.print(" * ");
  61. }
  62.  
  63. System.out.print(base);
  64. firstTime = false;
  65. base = 2; // reset
  66. }
  67.  
  68. base++;
  69. }
  70.  
  71. System.out.println();
  72. }
  73.  
  74. }
Add Comment
Please, Sign In to add comment