Guest User

Ugly Number

a guest
Oct 30th, 2018
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.51 KB | None | 0 0
  1. /**
  2.  * This program inputs a number and checks whether the number entered is an ugly number or not.
  3.  * For more information, please visit: https://goo.gl/vkv3Rv
  4.  */
  5. import java.util.*;
  6. public class Ugly_Number
  7. {
  8.     static boolean isPrime(int num) //Function to check whether a number is prime or not.
  9.     {
  10.         int i,flag=1;
  11.         if(num == 2)
  12.             return true;
  13.         else
  14.         {
  15.         for(i=2;i<num;i++)
  16.         {
  17.             if(num%i == 0)
  18.             {
  19.                 flag = 0;
  20.                 break;
  21.             }
  22.         }
  23.         if(flag == 1)
  24.             return true;
  25.         else
  26.             return false;
  27.         }
  28.     }
  29.    
  30.     static ArrayList<Integer> findPrimeFactors(int num) //Function to return all the prime factors of a number.
  31.     {
  32.         ArrayList<Integer> list = new ArrayList<Integer>();
  33.         int i;
  34.         for(i=2;i<=num;i++)
  35.         {
  36.             if(num%i == 0 && isPrime(i))
  37.             {
  38.                 list.add(i);
  39.             }
  40.         }
  41.        
  42.         return list;
  43.     }
  44.    
  45.     public static void main(String[] args)
  46.     {
  47.         Scanner sc = new Scanner(System.in);
  48.         System.out.println("Please enter a number.");
  49.         int num = sc.nextInt();
  50.         ArrayList<Integer> list = findPrimeFactors(num);
  51.         if(num == 1) //1 is an ugly number by convention.
  52.         {
  53.             System.out.println(num+" is an ugly number.");
  54.         }
  55.         else
  56.         {
  57.             int i,flag=1;
  58.             for(i=0;i<list.size();i++)
  59.             {
  60.                 if(list.get(i) > 5) //Checking whether the number has any prime factors except 2, 3 and 5.
  61.                 {
  62.                     flag = 0;
  63.                     break;
  64.                 }
  65.             }
  66.            
  67.             if(flag == 1)
  68.                 System.out.println(num+" is an ugly number.");
  69.             else
  70.                 System.out.println(num+" is not an ugly number.");
  71.         }
  72.         sc.close();
  73.     }
  74. }
Add Comment
Please, Sign In to add comment