Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * This program inputs a number and checks whether the number entered is an ugly number or not.
- * For more information, please visit: https://goo.gl/vkv3Rv
- */
- import java.util.*;
- public class Ugly_Number
- {
- static boolean isPrime(int num) //Function to check whether a number is prime or not.
- {
- int i,flag=1;
- if(num == 2)
- return true;
- else
- {
- for(i=2;i<num;i++)
- {
- if(num%i == 0)
- {
- flag = 0;
- break;
- }
- }
- if(flag == 1)
- return true;
- else
- return false;
- }
- }
- static ArrayList<Integer> findPrimeFactors(int num) //Function to return all the prime factors of a number.
- {
- ArrayList<Integer> list = new ArrayList<Integer>();
- int i;
- for(i=2;i<=num;i++)
- {
- if(num%i == 0 && isPrime(i))
- {
- list.add(i);
- }
- }
- return list;
- }
- public static void main(String[] args)
- {
- Scanner sc = new Scanner(System.in);
- System.out.println("Please enter a number.");
- int num = sc.nextInt();
- ArrayList<Integer> list = findPrimeFactors(num);
- if(num == 1) //1 is an ugly number by convention.
- {
- System.out.println(num+" is an ugly number.");
- }
- else
- {
- int i,flag=1;
- for(i=0;i<list.size();i++)
- {
- if(list.get(i) > 5) //Checking whether the number has any prime factors except 2, 3 and 5.
- {
- flag = 0;
- break;
- }
- }
- if(flag == 1)
- System.out.println(num+" is an ugly number.");
- else
- System.out.println(num+" is not an ugly number.");
- }
- sc.close();
- }
- }
Add Comment
Please, Sign In to add comment