Advertisement
RitinMalhotra

Composite Magic Number Range

Oct 29th, 2018
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.74 KB | None | 0 0
  1. /**
  2.  * This program inputs two numbers and prints the composite magic numbers in the entered range (Start and end included).
  3.  * For more information, please visit: https://goo.gl/XsZQ4p .
  4.  */
  5. import java.util.Scanner;
  6. public class Magic_Composite_Range
  7. {
  8.     static boolean isComposite(int num)
  9.     {
  10.         if(num == 2)
  11.             return false;
  12.        
  13.         int i,flag = 0;
  14.         for(i=2;i<num;i++)
  15.         {
  16.             if(num%i==0)
  17.             {
  18.                 flag=1;
  19.                 break;
  20.             }
  21.         }
  22.        
  23.         if(flag == 1)
  24.             return true;
  25.         else
  26.             return false;
  27.     }
  28.    
  29.     static int digitSum(int num)
  30.     {
  31.         String a = Integer.toString(num);
  32.         int i,x,sum=0;
  33.         for(i=0;i<a.length();i++)
  34.         {
  35.             x = Character.getNumericValue(a.charAt(i));
  36.             sum += x;
  37.         }
  38.        
  39.         return sum;
  40.     }
  41.    
  42.     static boolean isMagic(int num)
  43.     {
  44.         int sum = 0;
  45.         sum = digitSum(num);
  46.         while(sum > 9)  //Since any number <=9 can't have the sum of 1 unless it is 1 itself.
  47.         {
  48.             sum = digitSum(sum); //Finding the eventual sum.
  49.         }
  50.         if(sum == 1)
  51.             return true;
  52.         else
  53.             return false;
  54.     }
  55.    
  56.     public static void main(String[] args)
  57.     {
  58.         Scanner sc = new Scanner(System.in);
  59.         System.out.println("Please enter the lower limit.");
  60.         int start = sc.nextInt();
  61.         System.out.println("Please enter the upper limit.");
  62.         int end = sc.nextInt();
  63.         System.out.println();
  64.        
  65.         if(start<end)
  66.         {
  67.             int i,ct=0;
  68.             for(i=start;i<=end;i++)
  69.             {
  70.                 boolean check1 = isComposite(i);
  71.                 boolean check2 = isMagic(i);
  72.                 if(check1 && check2)
  73.                 {
  74.                     System.out.print(i+" | ");
  75.                     ct++;
  76.                 }
  77.             }
  78.             System.out.println("\nNumber of composite magic numbers between "+start+" and "+end+" = "+ct);
  79.         }
  80.        
  81.         else
  82.             System.out.println("Incorrect input. The lower limit must be lesser than the upper limit.");
  83.        
  84.         sc.close();
  85.     }
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement