What is a nasty number? Well it is a number whose four different factors can be arranged in such a way that sum of two is equal to difference of other two. Take an example of nasty number 36. It have factors 1,2,3,4,6,9,12,18. So, we have 2+1=6-3 . So, it is a nasty number.
Main class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import java.util.Scanner; class NastyMain{ public static void main(String args[]){ Scanner br = new Scanner(System.in); char x='y'; int num=0; NastyFinder Nasty = new NastyFinder(); do{ System.out.print("Enter the number you want to check : "); num = br.nextInt(); Nasty.isNasty(num); System.out.println("\n Do you want to check another number : y/anykey"); x=br.next().charAt(0); } while(x=='y' || x=='Y'); } } |
Nasty Number Finder Class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 |
class NastyFinder{ public void isNasty(int num){ // declare arrays int arr[] = new int[50]; // to store factors of given number int arrPlus[][] = new int[50][50]; // to store addition of factors int arrMinus[][] = new int[50][50]; // to store difference of factors // convert num to a positive if it's negative if(num<0){ num=num*(-1); } // find factors and store them int arIndex=0; // since arr will increase only we find any factors for(int i=1; i<(num/2); i++){ if((num%i)==0){ arr[arIndex] = i; arIndex++; } } // Add all the factors for(int i=0;i<arIndex;i++){ for(int j=0;j<arIndex;j++){ arrPlus[i][j] = arr[i] + arr[j]; } } // Save difference of all the factors for(int i=0;i<arIndex;i++){ for(int j=0;j<arIndex;j++){ arrMinus[i][j] = arr[i] - arr[j]; if(arrMinus[i][j]<0){ arrMinus[i][j]*=-1; } } } // now check each arrPlus and arrMinus elements if they are equal int a=0,b=0,c=0,d=0,yes=0; // for the purpose of traversing array elements outMostLoop: // this is a lable of next statement and not used for 'goto' for(int i=0; i<(arIndex * arIndex ); i++){ int comp1 = arrPlus[a][b]; for(int j=0; j<(arIndex * arIndex ); j++){ int comp2 = arrMinus[c][d]; if(comp1==comp2){ if(a!=b && a!=c && a!=d && b!=c && c!=d){ yes=1; //break outMostLoop; } } // increment d d++; // increment c on the bases of value of d if(d>=arIndex){ d=0; c++; } } // increment value of a and b like we have done with c and d c=0; d=0; b++; if(b>=arIndex){ b=0; a++; } } if(yes==1){ System.out.print("\n Yes it is a nasty number"); yes=0; } else{ System.out.print("\n No it is not a nasty number"); } }// isNasty closed } |