├── .gitattributes ├── .gitignore ├── Abbreviation.java ├── AngryProfessor.js ├── ArraysIntroduction.cpp ├── BasicCryptanalysis.java ├── BonAppetit.java ├── Bonetrousle.java ├── BotClean.cpp ├── BotCleanLarge.cpp ├── BotCleanStochastic.cpp ├── BotSavesPrincess.cpp ├── BreadthFirstSearchShortestReach.java ├── Cavity_Map.java ├── CombinationLock.java ├── DijkstraShortestReach2.java ├── FlippingTheMatrix.java ├── FunnyString.java ├── GameOfThronesI.java ├── GreedyFlorist.java ├── InsertionSortPart1.java ├── InsertionSortPart2.java ├── MaxXOR.java ├── NewYearChaos.java ├── NewYearGame.java ├── NewYearParty.java ├── Pairs.java ├── Pangrams.java ├── ProjectEulerPlus_Problem1.java ├── Project_Euler_Plus_Problem12.java ├── Project_Euler_Plus_Problem_1.java ├── Project_Euler_Plus_Problem_10.java ├── Project_Euler_Plus_Problem_11.java ├── Project_Euler_Plus_Problem_13.java ├── Project_Euler_Plus_Problem_14.java ├── Project_Euler_Plus_Problem_14b.java ├── Project_Euler_Plus_Problem_15.java ├── Project_Euler_Plus_Problem_16.java ├── Project_Euler_Plus_Problem_18.java ├── Project_Euler_Plus_Problem_2.java ├── Project_Euler_Plus_Problem_3.java ├── Project_Euler_Plus_Problem_4.java ├── Project_Euler_Plus_Problem_5.java ├── Project_Euler_Plus_Problem_6.java ├── Project_Euler_Plus_Problem_7.java ├── Project_Euler_Plus_Problem_8.java ├── Project_Euler_Plus_Problem_9.java ├── README.md ├── SherlockAndAnagrams.java ├── SherlockAndTheBeast.java ├── SparseArrays.java ├── TheMaximumSubarray.java ├── WeeklyChallenges_Week13_ASuperHero.java ├── WeeklyChallenges_Week13_TaumandBday.java ├── WeeklyChallenges_Week13_sherlockandanagrams.java ├── binarySearch.java ├── correctnessTestingInsertionSort.java ├── flipping_bits.java └── is_fibo.java /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | 7 | # Standard to msysgit 8 | *.doc diff=astextplain 9 | *.DOC diff=astextplain 10 | *.docx diff=astextplain 11 | *.DOCX diff=astextplain 12 | *.dot diff=astextplain 13 | *.DOT diff=astextplain 14 | *.pdf diff=astextplain 15 | *.PDF diff=astextplain 16 | *.rtf diff=astextplain 17 | *.RTF diff=astextplain 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Windows image file caches 2 | Thumbs.db 3 | ehthumbs.db 4 | 5 | # Folder config file 6 | Desktop.ini 7 | 8 | # Recycle Bin used on file shares 9 | $RECYCLE.BIN/ 10 | 11 | # Windows Installer files 12 | *.cab 13 | *.msi 14 | *.msm 15 | *.msp 16 | 17 | # Windows shortcuts 18 | *.lnk 19 | 20 | # ========================= 21 | # Operating System Files 22 | # ========================= 23 | 24 | # OSX 25 | # ========================= 26 | 27 | .DS_Store 28 | .AppleDouble 29 | .LSOverride 30 | 31 | # Thumbnails 32 | ._* 33 | 34 | # Files that might appear on external disk 35 | .Spotlight-V100 36 | .Trashes 37 | 38 | # Directories potentially created on remote AFP share 39 | .AppleDB 40 | .AppleDesktop 41 | Network Trash Folder 42 | Temporary Items 43 | .apdisk 44 | -------------------------------------------------------------------------------- /Abbreviation.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | //World CodeSpring 6, problem 4 5 | //https://www.hackerrank.com/contests/world-codesprint-6/challenges/abbr 6 | public class Abbreviation { 7 | 8 | static HashMap map; 9 | 10 | public static void main(String[] args) { 11 | // TODO Auto-generated method stub 12 | Scanner input = new Scanner(System.in); 13 | int q = input.nextInt(); 14 | for (int a = 0; a < q; a++) { 15 | 16 | map = new HashMap(); 17 | String strA = input.next(); 18 | String strB = input.next(); 19 | int idxA = 0; 20 | int idxB = 0; 21 | boolean OK = solve(strA, strB, idxA, idxB); 22 | //System.out.println(map); 23 | if(OK){ 24 | System.out.println("YES"); 25 | } 26 | else{ 27 | System.out.println("NO"); 28 | } 29 | } 30 | } 31 | 32 | private static boolean solve(String strA, String strB, int idxA, int idxB) { 33 | if(map.containsKey(hash(idxA, idxB))){ 34 | return map.get(hash(idxA, idxB)); 35 | } 36 | if(idxA == strA.length() && idxB == strB.length()){ 37 | //System.err.println(idxA + " " + idxB + " Good, both are done"); 38 | return true; 39 | } 40 | if(idxA == strA.length() && idxB != strB.length()){ 41 | 42 | //System.err.println(idxA + " " + idxB + " BAD, A finished before B"); 43 | return false; 44 | } 45 | if(idxB == strB.length() && idxA != strA.length()){ 46 | 47 | //System.err.println(idxA + " " + idxB + " removing lowercase"); 48 | //try and remove the rest of the strA's letters. 49 | boolean OK = false; 50 | if(isLowerCase(strA.charAt(idxA))){ 51 | OK = solve(strA, strB, idxA+1, idxB); 52 | } 53 | map.put(hash(idxA, idxB), OK); 54 | return OK; 55 | } 56 | 57 | if(isLowerCase(strA.charAt(idxA))){ 58 | //remove it or match 59 | //System.err.println(idxA + " " + idxB + " Lowercase"); 60 | boolean OK = solve(strA, strB, idxA+1, idxB); 61 | if(strA.charAt(idxA) == strB.charAt(idxB)-'A'+'a'){ 62 | OK = OK || solve(strA, strB, idxA+1, idxB+1); 63 | } 64 | map.put(hash(idxA, idxB), OK); 65 | return OK; 66 | } 67 | else{ 68 | //System.err.println(idxA + " " + idxB + " Uppercase"); 69 | boolean OK = false; 70 | if(strA.charAt(idxA) == strB.charAt(idxB)){ 71 | OK = OK || solve(strA, strB, idxA+1, idxB+1); 72 | } 73 | map.put(hash(idxA, idxB), OK); 74 | return OK; 75 | } 76 | } 77 | 78 | private static boolean isLowerCase(char charAt) { 79 | if(charAt-'a' >= 0 && charAt-'a' <= 25){ 80 | return true; 81 | } 82 | return false; 83 | } 84 | 85 | public static long hash(int a, int b) { 86 | return a * 1000000000l + b; 87 | } 88 | } -------------------------------------------------------------------------------- /AngryProfessor.js: -------------------------------------------------------------------------------- 1 | process.stdin.resume(); 2 | process.stdin.setEncoding('ascii'); 3 | //https://www.hackerrank.com/challenges/angry-professor 4 | var input_stdin = ""; 5 | var input_stdin_array = ""; 6 | var input_currentline = 0; 7 | 8 | process.stdin.on('data', function (data) { 9 | input_stdin += data; 10 | }); 11 | 12 | process.stdin.on('end', function () { 13 | input_stdin_array = input_stdin.split("\n"); 14 | main(); 15 | }); 16 | 17 | function readLine() { 18 | return input_stdin_array[input_currentline++]; 19 | } 20 | 21 | /////////////// ignore above this line //////////////////// 22 | 23 | function main() { 24 | var t = parseInt(readLine()); 25 | for(var a0 = 0; a0 < t; a0++){ 26 | var n_temp = readLine().split(' '); 27 | var n = parseInt(n_temp[0]); 28 | var k = parseInt(n_temp[1]); 29 | a = readLine().split(' '); 30 | a = a.map(Number); 31 | var count = 0; 32 | for(var a2 = 0; a2 < n; a2++){ 33 | count += (a[a2]<=0)?1:0; 34 | } 35 | if(count >= k){ 36 | console.log("NO"); 37 | } 38 | else{ 39 | console.log("YES"); 40 | } 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /ArraysIntroduction.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | //https://www.hackerrank.com/challenges/arrays-introduction 9 | int main() { 10 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 11 | int n; 12 | cin >> n; 13 | int arr[n]; 14 | for(int a = 0; a < n; a++){ 15 | cin >> arr[a]; 16 | } 17 | for(int a = n-1; a >= 0; a--){ 18 | cout << arr[a] << " "; 19 | } 20 | return 0; 21 | } -------------------------------------------------------------------------------- /BasicCryptanalysis.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | //https://www.hackerrank.com/challenges/basic-cryptanalysis 4 | public class BasicCryptanalysis { 5 | 6 | public static void main(String[] args) throws FileNotFoundException { 7 | /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ 8 | 9 | Scanner input = new Scanner(new File("dictionary.lst")); 10 | ArrayList dict = new ArrayList(); 11 | HashMap, ArrayList> dictionary = new HashMap, ArrayList>(); 12 | while(input.hasNext()){ 13 | String tmp = input.next(); 14 | dict.add(tmp); 15 | ArrayList freqDistOfFreqDist = getFreqDistOfFreqDist(tmp); 16 | if(!dictionary.containsKey(freqDistOfFreqDist)){ 17 | dictionary.put(freqDistOfFreqDist, new ArrayList()); 18 | } 19 | dictionary.get(freqDistOfFreqDist).add(tmp); 20 | } 21 | 22 | input = new Scanner(System.in); 23 | ArrayList arr = new ArrayList(); 24 | ArrayList otherMap = new ArrayList(); 25 | 26 | while(input.hasNext()){ 27 | String temp = input.next(); 28 | arr.add(temp); 29 | otherMap.add("~"); 30 | } 31 | HashMap knownCharacters = new HashMap(); 32 | 33 | for(int asdf = 0; asdf < 100; asdf++){ 34 | for(int k = 0; k < arr.size(); k++){ 35 | String temp = arr.get(k); 36 | ArrayList freqDistOfFreqDist = getFreqDistOfFreqDist(temp); 37 | ArrayList possibilities = new ArrayList(); 38 | if(dictionary.containsKey(freqDistOfFreqDist)){ 39 | for(String i:dictionary.get(freqDistOfFreqDist)){ 40 | //temp is a potential map with i 41 | if(possibleMatch(temp, i, knownCharacters)){ 42 | possibilities.add(i); 43 | } 44 | } 45 | } 46 | if(asdf == 99 && possibilities.size() == 0){ 47 | String out = convert(temp, knownCharacters); 48 | otherMap.set(k, out); 49 | } 50 | else if(possibilities.size() == 1 || asdf == 99){ 51 | otherMap.set(k, possibilities.get(0)); 52 | for(int a = 0; a < possibilities.get(0).length(); a++){ 53 | knownCharacters.put(temp.charAt(a), possibilities.get(0).charAt(a)); 54 | } 55 | } 56 | } 57 | } 58 | System.err.println(knownCharacters); 59 | for(String i: otherMap){ 60 | System.out.print(i + " "); 61 | } 62 | System.out.println(); 63 | } 64 | public static boolean possibleMatch(String temp, String i, HashMap knownCharacters){ 65 | for(int a = 0; a < i.length(); a++){ 66 | if(knownCharacters.containsKey(temp.charAt(a))){ 67 | if(i.charAt(a) != knownCharacters.get(temp.charAt(a))){ 68 | return false; 69 | } 70 | } 71 | } 72 | return true; 73 | } 74 | public static String convert(String temp, HashMap knownCharacters){ 75 | StringBuilder output = new StringBuilder(); 76 | for(int a = 0; a < temp.length(); a++){ 77 | if(knownCharacters.containsKey(temp.charAt(a))){ 78 | output.append(knownCharacters.get(temp.charAt(a))); 79 | } 80 | else{ 81 | output.append(temp.charAt(a)); 82 | } 83 | } 84 | return output.toString(); 85 | } 86 | public static ArrayList getFreqDistOfFreqDist(String tmp){ 87 | int[] freqDist = new int[256]; 88 | for(int a = 0; a < tmp.length(); a++){ 89 | freqDist[tmp.charAt(a)]++; 90 | } 91 | int[] freqDistfreqDist = new int[tmp.length()+1]; 92 | for(int a = 0; a < 256; a++){ 93 | if(freqDist[a] != 0){ 94 | freqDistfreqDist[freqDist[a]]++; 95 | } 96 | } 97 | ArrayList ret = new ArrayList(); 98 | for(int a = 0; a < freqDistfreqDist.length; a++){ 99 | ret.add(freqDistfreqDist[a]); 100 | } 101 | return ret; 102 | } 103 | } -------------------------------------------------------------------------------- /BonAppetit.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | //World CodeSpring 6, problem 1 4 | //https://www.hackerrank.com/contests/world-codesprint-6/challenges/bon-appetit 5 | public class BonAppetit { 6 | 7 | public static void main(String[] args) { 8 | // TODO Auto-generated method stub 9 | Scanner input = new Scanner(System.in); 10 | int n = input.nextInt(); 11 | int k = input.nextInt(); 12 | int[] arr = new int[n]; 13 | for(int a = 0; a < n; a++){ 14 | arr[a] = input.nextInt(); 15 | } 16 | 17 | long sum = 0; 18 | for(int a = 0; a < n; a++){ 19 | sum += arr[a]; 20 | } 21 | sum -= arr[k]; 22 | sum = sum/2; 23 | long val = input.nextInt(); 24 | 25 | if(sum == val){ 26 | System.out.println("Bon Appetit"); 27 | } 28 | else{ 29 | System.out.println(val-sum); 30 | } 31 | } 32 | } -------------------------------------------------------------------------------- /Bonetrousle.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | //World CodeSpring 6, problem 5 5 | //https://www.hackerrank.com/contests/world-codesprint-6/challenges/bonetrousle/submissions/code/6820974 6 | 7 | public class Bonetrousle { 8 | 9 | public static void main(String[] args) { 10 | Scanner input = new Scanner(System.in); 11 | int t = input.nextInt(); 12 | for (int q = 0; q < t; q++) { 13 | long n = input.nextLong(); // number of sticks to buy 14 | long k = input.nextLong(); // boxes available for purchase 15 | long b = input.nextInt(); // boxes to buy 16 | 17 | // (x+1) + (x+2) + (x+3)...(x+b) 18 | // b*x + b*(b+1)/2 = n 19 | 20 | long temp = n - (b * (b + 1)) / 2; 21 | if (temp % b == 0) { 22 | temp = temp / b; 23 | } else { 24 | temp = temp / b + 1; // round up if necessary 25 | } 26 | // we want to take the boxes x+1, x+2, x+3, ... x+b. But we might 27 | // have some left over. 28 | 29 | long overbuy = temp * b + (b) * (b + 1) / 2 - n; 30 | long[] answers = new long[(int) b]; 31 | for (int a = 0; a < b; a++) { 32 | answers[a] = temp + a + 1; 33 | } 34 | for (int a = 1; a <= b; a++) { 35 | if (overbuy > 0) { 36 | if (overbuy > answers[a - 1] - a) { 37 | overbuy -= answers[a - 1] - a; 38 | answers[a - 1] = a; 39 | } else { 40 | answers[a - 1] -= overbuy; 41 | overbuy = 0; 42 | } 43 | } 44 | } 45 | long sum = 0; 46 | boolean OK = true; 47 | for (int a = 0; a < b; a++) { 48 | sum += answers[a]; 49 | if (answers[a] <= 0) { 50 | OK = false; 51 | } 52 | if (answers[a] > k) { 53 | OK = false; 54 | } 55 | } 56 | if(sum != n){ 57 | OK = false; 58 | } 59 | if (!OK) { 60 | System.out.println("-1"); 61 | } else { 62 | StringBuilder output = new StringBuilder(); 63 | for (int a = 0; a < b; a++) { 64 | output.append(answers[a]); 65 | if(a != b-1){ 66 | output.append(" "); 67 | } 68 | } 69 | System.out.println(output); 70 | } 71 | } 72 | } 73 | } -------------------------------------------------------------------------------- /BotClean.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | //https://www.hackerrank.com/challenges/botclean 5 | using namespace std; 6 | void next_move(int posr, int posc, vector board) { 7 | //let's greedily move towards the nearest dirt. 8 | 9 | queue bfs; 10 | bfs.push(posr*100+posc); 11 | bool visited[5][5]; 12 | for(int i = 0; i < 5; i++){ 13 | for(int j = 0; j < 5; j++){ 14 | visited[i][j] = false; 15 | } 16 | } 17 | int ansX = -1; 18 | int ansY = -1; 19 | int count = 0; 20 | cerr << "START " << posr << " " << posc << "\n"; 21 | while(!bfs.empty()){ 22 | 23 | count++; 24 | int temp = bfs.front(); 25 | bfs.pop(); 26 | int tempX = temp/100; 27 | int tempY = temp%100; 28 | cerr << tempX << " " << tempY << "\n"; 29 | if(board[tempX][tempY] == 'd'){ 30 | ansX = tempX; 31 | ansY = tempY; 32 | break; 33 | } 34 | 35 | visited[tempX][tempY] = true; 36 | if(tempX > 0){ 37 | if(!visited[tempX-1][tempY]){ 38 | bfs.push((tempX-1)*100 + tempY); 39 | } 40 | } 41 | if(tempX < 4){ 42 | if(!visited[tempX+1][tempY]){ 43 | bfs.push((tempX+1)*100 + tempY); 44 | } 45 | } 46 | if(tempY > 0){ 47 | if(!visited[tempX][tempY-1]){ 48 | bfs.push((tempX)*100 + tempY-1); 49 | } 50 | } 51 | if(tempY < 4){ 52 | if(!visited[tempX][tempY+1]){ 53 | bfs.push((tempX)*100 + tempY+1); 54 | } 55 | } 56 | 57 | 58 | 59 | } 60 | 61 | //go toward dirt once we find it. 62 | int startX = posr; 63 | int startY = posc; 64 | int endX = ansX; 65 | int endY = ansY; 66 | 67 | if(startX < endX){ 68 | cout << "DOWN"; 69 | } 70 | else if(startX > endX){ 71 | cout << "UP"; 72 | } 73 | else if(startY < endY){ 74 | cout << "RIGHT"; 75 | } 76 | else if(startY > endY){ 77 | cout << "LEFT"; 78 | } 79 | else{ 80 | cout << "CLEAN"; 81 | } 82 | } 83 | int main(void) { 84 | int pos[2]; 85 | vector board; 86 | cin>>pos[0]>>pos[1]; 87 | for(int i=0;i<5;i++) { 88 | string s;cin >> s; 89 | board.push_back(s); 90 | } 91 | next_move(pos[0], pos[1], board); 92 | return 0; 93 | } 94 | -------------------------------------------------------------------------------- /BotCleanLarge.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | //https://www.hackerrank.com/challenges/botcleanlarge 5 | using namespace std; 6 | void next_move(int posr, int posc, int dimh, int dimw, vector board) { 7 | //let's greedily move towards the nearest dirt. 8 | queue bfs; 9 | bfs.push(posr*100+posc); 10 | bool visited[dimh][dimw]; 11 | for(int i = 0; i < dimh; i++){ 12 | for(int j = 0; j < dimw; j++){ 13 | visited[i][j] = false; 14 | } 15 | } 16 | int ansX = -1; 17 | int ansY = -1; 18 | int count = 0; 19 | cerr << "START " << posr << " " << posc << "\n"; 20 | while(!bfs.empty()){ 21 | 22 | count++; 23 | int temp = bfs.front(); 24 | bfs.pop(); 25 | int tempX = temp/100; 26 | int tempY = temp%100; 27 | if(board[tempX][tempY] == 'd'){ 28 | ansX = tempX; 29 | ansY = tempY; 30 | break; 31 | } 32 | 33 | visited[tempX][tempY] = true; 34 | if(tempX > 0){ 35 | if(!visited[tempX-1][tempY]){ 36 | bfs.push((tempX-1)*100 + tempY); 37 | } 38 | } 39 | if(tempX < dimh-1){ 40 | if(!visited[tempX+1][tempY]){ 41 | cerr << tempX << " " << dimw << "\n"; 42 | bfs.push((tempX+1)*100 + tempY); 43 | } 44 | } 45 | if(tempY > 0){ 46 | if(!visited[tempX][tempY-1]){ 47 | bfs.push((tempX)*100 + tempY-1); 48 | } 49 | } 50 | if(tempY < dimw-1){ 51 | if(!visited[tempX][tempY+1]){ 52 | bfs.push((tempX)*100 + tempY+1); 53 | } 54 | } 55 | 56 | 57 | 58 | } 59 | 60 | //go toward dirt once we find it. 61 | int startX = posr; 62 | int startY = posc; 63 | int endX = ansX; 64 | int endY = ansY; 65 | 66 | if(startX < endX){ 67 | cout << "DOWN"; 68 | } 69 | else if(startX > endX){ 70 | cout << "UP"; 71 | } 72 | else if(startY < endY){ 73 | cout << "RIGHT"; 74 | } 75 | else if(startY > endY){ 76 | cout << "LEFT"; 77 | } 78 | else{ 79 | cout << "CLEAN"; 80 | } 81 | } 82 | int main(void) { 83 | int pos[2]; 84 | int dim[2]; 85 | vector board; 86 | cin>>pos[0]>>pos[1]; 87 | cin>>dim[0]>>dim[1]; 88 | for(int i=0;i> s; 90 | board.push_back(s); 91 | } 92 | next_move(pos[0], pos[1], dim[0], dim[1], board); 93 | return 0; 94 | } -------------------------------------------------------------------------------- /BotCleanStochastic.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | //https://www.hackerrank.com/challenges/botcleanr 5 | using namespace std; 6 | void nextMove(int posr, int posc, vector board) { 7 | //let's greedily move towards the nearest dirt. 8 | 9 | queue bfs; 10 | bfs.push(posr*100+posc); 11 | bool visited[5][5]; 12 | for(int i = 0; i < 5; i++){ 13 | for(int j = 0; j < 5; j++){ 14 | visited[i][j] = false; 15 | } 16 | } 17 | int ansX = -1; 18 | int ansY = -1; 19 | int count = 0; 20 | cerr << "START " << posr << " " << posc << "\n"; 21 | while(!bfs.empty()){ 22 | 23 | count++; 24 | int temp = bfs.front(); 25 | bfs.pop(); 26 | int tempX = temp/100; 27 | int tempY = temp%100; 28 | cerr << tempX << " " << tempY << "\n"; 29 | if(board[tempX][tempY] == 'd'){ 30 | ansX = tempX; 31 | ansY = tempY; 32 | break; 33 | } 34 | 35 | visited[tempX][tempY] = true; 36 | if(tempX > 0){ 37 | if(!visited[tempX-1][tempY]){ 38 | bfs.push((tempX-1)*100 + tempY); 39 | } 40 | } 41 | if(tempX < 4){ 42 | if(!visited[tempX+1][tempY]){ 43 | bfs.push((tempX+1)*100 + tempY); 44 | } 45 | } 46 | if(tempY > 0){ 47 | if(!visited[tempX][tempY-1]){ 48 | bfs.push((tempX)*100 + tempY-1); 49 | } 50 | } 51 | if(tempY < 4){ 52 | if(!visited[tempX][tempY+1]){ 53 | bfs.push((tempX)*100 + tempY+1); 54 | } 55 | } 56 | 57 | 58 | 59 | } 60 | 61 | //go toward dirt once we find it. 62 | int startX = posr; 63 | int startY = posc; 64 | int endX = ansX; 65 | int endY = ansY; 66 | 67 | if(startX < endX){ 68 | cout << "DOWN"; 69 | } 70 | else if(startX > endX){ 71 | cout << "UP"; 72 | } 73 | else if(startY < endY){ 74 | cout << "RIGHT"; 75 | } 76 | else if(startY > endY){ 77 | cout << "LEFT"; 78 | } 79 | else{ 80 | cout << "CLEAN"; 81 | } 82 | } 83 | int main(void) { 84 | int pos[2]; 85 | vector board; 86 | cin>>pos[0]>>pos[1]; 87 | for(int i=0;i<5;i++) { 88 | string s; 89 | cin >> s; 90 | board.push_back(s); 91 | } 92 | nextMove(pos[0], pos[1], board); 93 | return 0; 94 | } -------------------------------------------------------------------------------- /BotSavesPrincess.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | //https://www.hackerrank.com/challenges/saveprincess 4 | using namespace std; 5 | void displayPathtoPrincess(int n, vector grid){ 6 | int startX; 7 | int startY; 8 | int endX; 9 | int endY; 10 | for(int a = 0; a < n; a++){ 11 | for(int b = 0; b < n; b++){ 12 | if(grid[a][b] == 'm'){ 13 | startX = a; 14 | startY = b; 15 | } 16 | if(grid[a][b] == 'p'){ 17 | endX = a; 18 | endY = b; 19 | } 20 | } 21 | } 22 | while(startX < endX){ 23 | cout << "DOWN\n"; 24 | startX++; 25 | } 26 | while(startX > endX){ 27 | cout << "UP\n"; 28 | startX--; 29 | } 30 | while(startY < endY){ 31 | cout << "RIGHT\n"; 32 | startY++; 33 | } 34 | while(startY > endY){ 35 | cout << "LEFT\n"; 36 | startY--; 37 | } 38 | } 39 | int main(void) { 40 | 41 | int m; 42 | vector grid; 43 | 44 | cin >> m; 45 | 46 | for(int i=0; i> s; 48 | grid.push_back(s); 49 | } 50 | 51 | displayPathtoPrincess(m,grid); 52 | 53 | return 0; 54 | } -------------------------------------------------------------------------------- /BreadthFirstSearchShortestReach.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | import java.text.*; 4 | import java.math.*; 5 | import java.util.regex.*; 6 | import java.util.concurrent.*; 7 | //https://www.hackerrank.com/challenges/bfsshortreach 8 | public class BreadthFirstSearchShortestReach { 9 | 10 | public static void calculate_cost(Scanner sc){ 11 | 12 | // build list 13 | int N = sc.nextInt(); 14 | int M = sc.nextInt(); 15 | ArrayList[] graph = (ArrayList[]) new ArrayList[N]; 16 | int[] dist = new int[N]; 17 | for (int i = 0; i < M; i++) { 18 | int key = sc.nextInt() - 1; 19 | int rot = sc.nextInt() - 1; 20 | if (graph[key] == null) { 21 | graph[key] = new ArrayList(); 22 | } 23 | if (graph[rot] == null) { 24 | graph[rot] = new ArrayList(); 25 | } 26 | graph[key].add(rot); 27 | graph[rot].add(key); 28 | } 29 | int start = sc.nextInt(); 30 | dist[start-1] = 5; // if 5 found later then it is know to be start 31 | 32 | 33 | // start traversal 34 | LinkedBlockingQueue todo = new LinkedBlockingQueue(); 35 | LinkedBlockingQueue cost = new LinkedBlockingQueue(); 36 | todo.offer(start-1); 37 | cost.offer(0); 38 | while(todo.size()!=0){ 39 | int at = (int)todo.poll(); 40 | int depth = (int)cost.poll(); 41 | if (dist[at] == 0){ 42 | dist[at] = 6 * depth; 43 | if (graph[at] != null){ 44 | for(int i = 0; i < graph[at].size(); i++){ 45 | todo.offer(graph[at].get(i)); 46 | cost.offer(depth+1); 47 | } 48 | } 49 | } else if (dist[at] == 5){ 50 | if (graph[at] != null){ 51 | for(int i = 0; i < graph[at].size(); i++){ 52 | todo.offer(graph[at].get(i)); 53 | cost.offer(depth+1); 54 | } 55 | } 56 | } 57 | } 58 | 59 | for(int i = 0; i < dist.length; i++){ 60 | if (dist[i] == 5){ 61 | continue; 62 | } else if (dist[i] == 0){ 63 | System.out.print("-1 "); 64 | } else { 65 | System.out.print(dist[i]+" "); 66 | } 67 | } 68 | System.out.println(); 69 | 70 | } 71 | 72 | public static void main(String[] args) { 73 | /* Enter your code here. Read input from STDIN. Print output to STDOUT. */ 74 | Scanner sc = new Scanner(System.in); 75 | int T = sc.nextInt(); 76 | for(int i = 0; i < T; i++){ 77 | calculate_cost(sc); 78 | } 79 | } 80 | } -------------------------------------------------------------------------------- /Cavity_Map.java: -------------------------------------------------------------------------------- 1 | import java.math.BigInteger; 2 | import java.util.Scanner; 3 | 4 | public class Cavity_Map { 5 | /* 6 | * Problem Statement 7 | 8 | You are given a square n×n map. Each cell of the map has a value in it denoting the depth of the appropriate area. We will call a cell of the map a cavity if and only if this cell is not on the border of the map and each cell adjacent to it has strictly smaller depth. Two cells are adjacent if they have a common side. 9 | 10 | You need to find all the cavities on the map and depict them with character uppercase X. 11 | 12 | Input Format 13 | 14 | The first line contains an integer n (1≤n≤100), denoting the size of the map. Each of the following n lines contains n positive digits without spaces. A digit (1-9) denotes the depth of the appropriate area. 15 | 16 | Output Format 17 | 18 | Output n lines, denoting the resulting map. Each cavity should be replaced with character X. 19 | */ 20 | public static void main(String[] args) { 21 | Scanner stdin = new Scanner(System.in); 22 | int numberOfCases = Integer.parseInt(stdin.nextLine()); 23 | String input[] = new String[numberOfCases]; 24 | for (int a = 0; a < numberOfCases; a++) { 25 | input[a] = stdin.nextLine(); 26 | } 27 | for (int a = 0; a < numberOfCases; a++) { 28 | for (int b = 0; b < numberOfCases; b++) { 29 | if (isOnEdge(a, b, numberOfCases)) { 30 | input[a] = input[a].substring(0, b) + input[a].charAt(b) 31 | + input[a].substring(b + 1, numberOfCases); 32 | } else { 33 | input[a] = input[a].substring(0, b) 34 | + (isCavity(b, a, input) ? 'X' : input[a].charAt(b)) 35 | + input[a].substring(b + 1, numberOfCases); 36 | } 37 | } 38 | System.out.println(input[a]); 39 | } 40 | } 41 | 42 | public static boolean isOnEdge(int x, int y, int size) { 43 | 44 | return (x == 0 || y == 0 || x == size - 1 || y == size - 1); 45 | // x and y cannot be zero or size-1 respectively 46 | } 47 | 48 | public static boolean isCavity(int x, int y, String[] input) { 49 | 50 | if (input[y].charAt(x - 1) >= input[y].charAt(x) 51 | || input[y].charAt(x - 1) == 'X') { 52 | return false; 53 | } 54 | 55 | if (input[y].charAt(x + 1) >= input[y].charAt(x) 56 | || input[y].charAt(x + 1) == 'X') { 57 | return false; 58 | } 59 | 60 | if (input[y - 1].charAt(x) >= input[y].charAt(x) 61 | || input[y - 1].charAt(x) == 'X') { 62 | return false; 63 | } 64 | 65 | if (input[y + 1].charAt(x) >= input[y].charAt(x) 66 | || input[y + 1].charAt(x) == 'X') { 67 | return false; 68 | } 69 | return true; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /CombinationLock.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | //World CodeSpring 6, problem 2 4 | //https://www.hackerrank.com/contests/world-codesprint-6/challenges/combination-lock 5 | public class CombinationLock { 6 | 7 | public static void main(String[] args) { 8 | // TODO Auto-generated method stub 9 | Scanner input = new Scanner(System.in); 10 | int[] arr1 = new int[5]; 11 | int[] arr2 = new int[5]; 12 | for(int a = 0; a < 5; a++){ 13 | arr1[a] = input.nextInt(); 14 | } 15 | for(int a = 0; a < 5; a++){ 16 | arr2[a] = input.nextInt(); 17 | } 18 | int sum = 0; 19 | for(int a = 0; a < 5; a++){ 20 | sum += Math.min(Math.min(Math.abs(arr1[a]-arr2[a]), Math.abs(arr1[a]+10-arr2[a])), Math.abs(arr2[a]+10-arr1[a])); 21 | } 22 | System.out.println(sum); 23 | } 24 | } -------------------------------------------------------------------------------- /DijkstraShortestReach2.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | import java.text.*; 4 | import java.math.*; 5 | import java.util.regex.*; 6 | //https://www.hackerrank.com/challenges/dijkstrashortreach 7 | 8 | 9 | // since we only care about min values for least costly 10 | // path then we can remove duplicate edges that are more costly 11 | 12 | public class DijkstraShortestReach2 { 13 | 14 | public static int next(int[] dist, Boolean[] done){ 15 | int smallest_cost = Integer.MAX_VALUE; 16 | int closest = -1; 17 | for (int i =0; i < dist.length; i++){ 18 | if (!done[i] && dist[i] <= smallest_cost){ 19 | smallest_cost = dist[i]; 20 | closest = i; 21 | } 22 | } 23 | return closest; 24 | } 25 | 26 | public static void dj(int[][] g, Scanner in){ 27 | int start = in.nextInt() -1; 28 | int num_v = g.length; 29 | int[] cost = new int[num_v]; 30 | Boolean[] visited = new Boolean[num_v]; 31 | 32 | for (int i = 0; i < num_v; i++){ 33 | visited[i] = false; 34 | cost[i] = Integer.MAX_VALUE; 35 | } 36 | 37 | cost[start] = 0; 38 | 39 | for (int done = 0; done < num_v -1; done++){ 40 | int nxt = next(cost, visited); 41 | visited[nxt] = true; 42 | 43 | for (int peer = 0; peer < num_v; peer++){ 44 | if (!visited[peer] && g[nxt][peer] != 0 && 45 | cost[nxt] != (Integer.MAX_VALUE) && 46 | cost[nxt]+g[nxt][peer] < cost[peer]){ 47 | cost[peer] = cost[nxt]+g[nxt][peer]; 48 | } 49 | } 50 | } 51 | 52 | for (int i = 0; i < num_v; i++){ 53 | if (cost[i] != 0 && cost[i]!= (Integer.MAX_VALUE)){ 54 | System.out.print(cost[i]+" "); 55 | } else if (cost[i] == (Integer.MAX_VALUE)){ 56 | System.out.print("-1 "); 57 | } 58 | } 59 | System.out.println(); 60 | 61 | } 62 | 63 | public static int[][] build_graph(Scanner in){ 64 | int n = in.nextInt(); 65 | int e = in.nextInt(); 66 | int[][] g = new int[n][n]; 67 | for(int i = 0; i < e; i++){ 68 | int x = in.nextInt() - 1; 69 | int y = in.nextInt() - 1; 70 | int w = in.nextInt(); 71 | if (g[x][y] == 0 || g[x][y] > w){ 72 | g[x][y] = w; 73 | g[y][x] = w; 74 | } 75 | } 76 | return g; 77 | 78 | } 79 | 80 | public static void main(String[] args) { 81 | Scanner sc = new Scanner(System.in); 82 | int t = sc.nextInt(); 83 | for (int i = 0; i < t; i++){ 84 | int[][] graph = build_graph(sc); 85 | dj(graph, sc); 86 | } 87 | } 88 | } -------------------------------------------------------------------------------- /FlippingTheMatrix.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | //World CodeSpring 6, problem 3 4 | //https://www.hackerrank.com/contests/world-codesprint-6/challenges/flipping-the-matrix 5 | public class FlippingTheMatrix { 6 | 7 | public static void main(String[] args) { 8 | // TODO Auto-generated method stub 9 | Scanner input = new Scanner(System.in); 10 | int q = input.nextInt(); 11 | for(int a = 0; a < q; a++){ 12 | int n = input.nextInt(); 13 | int[][] arr = new int[2*n][2*n]; 14 | for(int b = 0; b < 2*n; b++){ 15 | for(int c =0 ; c < 2*n; c++){ 16 | arr[b][c] = input.nextInt(); 17 | } 18 | } 19 | long sum = 0; 20 | for(int b = 0; b < n; b++){ 21 | for(int c = 0; c < n; c++){ 22 | sum += Math.max(Math.max(arr[b][c], arr[2*n-b-1][c]), Math.max(arr[b][2*n-c-1], arr[2*n-b-1][2*n-c-1])); 23 | } 24 | } 25 | System.out.println(sum); 26 | } 27 | } 28 | 29 | } -------------------------------------------------------------------------------- /FunnyString.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | //https://www.hackerrank.com/challenges/funny-string 4 | public class FunnyString { 5 | 6 | public static void main(String[] args) { 7 | Scanner input = new Scanner(System.in); 8 | int n = input.nextInt(); 9 | input.nextLine(); 10 | for(int a = 0; a < n; a++){ 11 | String n2 = input.nextLine(); 12 | boolean ok = true; 13 | for(int b = 0; b < n2.length()-1; b++){ 14 | if(Math.abs(n2.charAt(b)-n2.charAt(b+1))!=Math.abs(n2.charAt(n2.length()-1-b)-n2.charAt(n2.length()-1-b-1))){ 15 | ok = false; 16 | } 17 | } 18 | if(ok){ 19 | System.out.println("Funny"); 20 | } 21 | else{ 22 | System.out.println("Not Funny"); 23 | } 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /GameOfThronesI.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | //https://www.hackerrank.com/challenges/game-of-thrones 4 | public class GameOfThronesI { 5 | 6 | public static void main(String[] args) { 7 | Scanner input= new Scanner(System.in); 8 | String a2 = input.nextLine(); 9 | int length = a2.length(); 10 | int[] freqDist = new int[500]; 11 | for(int a = 0; a < length; a++){ 12 | freqDist[a2.charAt(a)]++; 13 | } 14 | int oddCount = 0; 15 | for(int a = 0; a < freqDist.length; a++){ 16 | if(freqDist[a]%2==1){ 17 | oddCount++; 18 | } 19 | } 20 | if((length%2 == 0 && oddCount == 0) || (length%2==1 && oddCount == 1)){ 21 | System.out.println("YES"); 22 | } 23 | else{ 24 | System.out.println("NO"); 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /GreedyFlorist.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | //https://www.hackerrank.com/challenges/greedy-florist 4 | public class GreedyFlorist { 5 | 6 | public static void main(String[] args) { 7 | Scanner input = new Scanner(System.in); 8 | int n = input.nextInt(); 9 | int k = input.nextInt(); 10 | int[] test = new int[n]; 11 | for(int a = 0; a < n; a++){ 12 | test[a] = input.nextInt(); 13 | } 14 | Arrays.sort(test); 15 | long count = 0; 16 | for(int a = 0; a < n; a++){ 17 | count += test[n-1-a]*((a/k) + 1); 18 | } 19 | System.out.println(count); 20 | } 21 | } -------------------------------------------------------------------------------- /InsertionSortPart1.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | public class InsertionSortPart1 { 3 | /** 4 | * Insertion Sort 5 | These challenges will cover Insertion Sort, a simple and intuitive sorting algorithm. We will first start with an already sorted list. 6 | 7 | Insert element into sorted list 8 | Given a sorted list with an unsorted number V in the right-most cell, can you write some simple code to insert V into the array so it remains sorted? 9 | 10 | Print the array every time a value is shifted in the array until the array is fully sorted. The goal of this challenge is to follow the correct order of insertion sort. 11 | 12 | Guideline: You can copy the value of V to a variable, and consider its cell "empty". Since this leaves an extra cell empty on the right, you can shift everything over until V can be inserted. This will create a duplicate of each value, but when you reach the right spot, you can replace a value with V. 13 | 14 | Input Format 15 | There will be two lines of input: 16 | 17 | s - the size of the array 18 | ar - the sorted array of integers 19 | Output Format 20 | On each line, output the entire array every time an item is shifted in it. 21 | 22 | Constraints 23 | 1<=s<=1000 24 | -10000<=x<= 10000, x ar 25 | */ 26 | public static void main(String[] args) { 27 | Scanner stdin = new Scanner(System.in); 28 | int lengthOfList= Integer.parseInt(stdin.nextLine()); 29 | int[] input = new int[lengthOfList]; 30 | for (int a = 0; a < lengthOfList; a++) { 31 | input[a] = stdin.nextInt(); 32 | } 33 | int temp = input[lengthOfList-1]; 34 | int a = lengthOfList - 2; 35 | while(a > -1 && a < lengthOfList && temp < input[a]){ //while position has not been found, we 36 | input[a+1] = input[a]; //shift the elements over 37 | for(int b = 0; b < lengthOfList; b++){ //print the list 38 | System.out.print(input[b] + " "); 39 | } 40 | System.out.println(); 41 | a--; //iterate the variable. 42 | } 43 | input[a+1] = temp; //set in final position 44 | for(int b = 0; b < lengthOfList; b++){ 45 | System.out.print(input[b] + " "); //print final list 46 | } 47 | System.out.println(); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /InsertionSortPart2.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class InsertionSortPart2 { 4 | public static void main(String[] args) { 5 | Scanner stdin = new Scanner(System.in); 6 | int lengthOfList = Integer.parseInt(stdin.nextLine()); 7 | int[] input = new int[lengthOfList]; 8 | for (int a = 0; a < lengthOfList; a++) { 9 | input[a] = stdin.nextInt(); 10 | } 11 | if (lengthOfList > 1){ 12 | int b = 2; 13 | while(b <= lengthOfList){ 14 | input = merge(insertionSort(subarray(input, 0, b), b), subarray(input, b, lengthOfList)); 15 | printArray(input); 16 | b++; 17 | } 18 | } 19 | else{ 20 | System.out.println(input[0]); 21 | } 22 | 23 | 24 | } 25 | public static void printArray(int[] input){ 26 | for(int b = 0; b < input.length; b++){ 27 | System.out.print(input[b] + " "); 28 | } 29 | System.out.println(); 30 | } 31 | public static int[] insertionSort(int[] input, int lengthOfList) { 32 | int temp = input[lengthOfList - 1]; 33 | int a = lengthOfList - 2; 34 | while (a > -1 && a < lengthOfList && temp < input[a]) { // while 35 | // position has 36 | // not been 37 | // found, we 38 | input[a + 1] = input[a]; // shift the elements over 39 | a--; // iterate the variable. 40 | } 41 | input[a + 1] = temp; 42 | return input; 43 | } 44 | public static int[] subarray(int[] array, int start, int end){ //includes start but not end 45 | int [] output = new int[end-start]; 46 | for(int a = 0; a < output.length; a++){ 47 | output[a] = array[start + a]; 48 | } 49 | return output; 50 | } 51 | public static int[] merge(int[] array, int[] array2){ 52 | int length = array.length + array2.length; 53 | int ret[] = new int[length]; 54 | for(int a = 0; a < array.length; a++){ 55 | ret[a] = array[a]; 56 | } 57 | for(int b = 0; b < array2.length; b++){ 58 | ret[array.length + b] = array2[b]; 59 | } 60 | return ret; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /MaxXOR.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | //https://www.hackerrank.com/challenges/maximizing-xor 4 | public class MaxXOR { 5 | 6 | public static void main(String[] args) { 7 | Scanner input = new Scanner(System.in); 8 | int n = input.nextInt(); 9 | int e = input.nextInt(); 10 | int max = 0; 11 | for(int k = n; k <= e; k++){ 12 | for(int j = n; j<= e; j++){ 13 | if(max < (j^k)){ 14 | max = (j^k); 15 | } 16 | } 17 | } 18 | System.out.println(max); 19 | } 20 | } -------------------------------------------------------------------------------- /NewYearChaos.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | //https://www.hackerrank.com/contests/hourrank-4/challenges/new-year-chaos 3 | public class NewYearChaos { 4 | public static void main(String[] args) { 5 | Scanner input = new Scanner(System.in); 6 | int testCases = input.nextInt(); 7 | while (testCases > 0) { 8 | testCases--; 9 | int n = input.nextInt(); 10 | int[] inputLine = new int[n]; 11 | for (int a = 0; a < n; a++) { 12 | inputLine[a] = input.nextInt(); 13 | } 14 | int[] outputFrequencyDistribution = new int[n + 1]; 15 | boolean chaos = false; 16 | boolean finished = false; 17 | int count = 0; 18 | while (!finished) { 19 | finished = true; 20 | for (int a = 0; a < n - 1; a++) { 21 | if (inputLine[a] > inputLine[a + 1]) { 22 | outputFrequencyDistribution[inputLine[a]]++; 23 | if (outputFrequencyDistribution[inputLine[a]] > 2) { 24 | finished = true; 25 | chaos = true; // if it's too chaotic, break out 26 | break; 27 | } 28 | count++; 29 | int temp = inputLine[a]; 30 | inputLine[a] = inputLine[a + 1]; 31 | inputLine[a + 1] = temp; 32 | finished = false; 33 | } 34 | } 35 | } 36 | if (chaos) { 37 | System.out.println("Too chaotic"); 38 | } else { 39 | System.out.println(count); 40 | } 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /NewYearGame.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | //https://www.hackerrank.com/contests/hourrank-4/challenges/newyear-game 3 | public class NewYearGame { 4 | public static void main(String[] args) { 5 | Scanner input = new Scanner(System.in); 6 | int testCases = input.nextInt(); 7 | while (testCases > 0) { 8 | testCases--; 9 | int n = input.nextInt(); 10 | boolean[] inputLine = new boolean[3]; 11 | for (int a = 0; a < n; a++) { 12 | int temp = input.nextInt(); 13 | inputLine[temp%3] = !inputLine[temp%3]; 14 | } 15 | if((!inputLine[1]) && (!inputLine[2])){ 16 | System.out.println("Koca"); 17 | } 18 | else{ 19 | System.out.println("Balsa"); 20 | } 21 | 22 | 23 | 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /NewYearParty.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | //https://www.hackerrank.com/contests/hourrank-4/challenges/new-year-party 4 | public class NewYearParty { 5 | public static void main(String[] args){ 6 | Scanner input = new Scanner(System.in); 7 | int n = input.nextInt(); 8 | int[] inputTimes = new int[n]; 9 | for(int a = 0; a < n; a++){ 10 | inputTimes[a] = input.nextInt(); 11 | } 12 | int time = 0; 13 | for(int a = 0; a < n; a++){ 14 | time = Math.max(time+1, inputTimes[a]); 15 | } 16 | System.out.println(time); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Pairs.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | import java.*; 4 | //https://www.hackerrank.com/challenges/pairs 5 | public class Pairs { 6 | 7 | public static void main(String[] args) { 8 | /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ 9 | Scanner input = new Scanner(System.in); 10 | int n = input.nextInt(); 11 | int goal = input.nextInt(); 12 | HashMap mapping = new HashMap(); 13 | HashSet noDuplicates = new HashSet(); 14 | for(int a = 0; a < n; a++){ 15 | int temp = input.nextInt(); 16 | noDuplicates.add(temp); 17 | if(mapping.containsKey(temp)){ 18 | mapping.put(temp, mapping.get(temp)+1); 19 | } 20 | else{ 21 | mapping.put(temp, 1); 22 | } 23 | } 24 | int[] newArr = new int[mapping.size()]; 25 | long count = 0; 26 | for(Integer a:noDuplicates){ 27 | if(mapping.containsKey(a+goal)){ 28 | count+=mapping.get(a+goal)*mapping.get(a); 29 | } 30 | } 31 | System.out.println(count); 32 | } 33 | } -------------------------------------------------------------------------------- /Pangrams.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | //https://www.hackerrank.com/challenges/pangrams 4 | public class Pangrams { 5 | 6 | public static void main(String[] args) { 7 | Scanner input = new Scanner(System.in); 8 | String in = input.nextLine(); 9 | int[] freqDist = new int[26]; 10 | for(int a = 0; a < in.length(); a++){ 11 | String sub = in.substring(a, a+1); 12 | sub = sub.toLowerCase(); 13 | if(!sub.equals(" ")){ 14 | freqDist[sub.charAt(0)-'a']++; 15 | } 16 | } 17 | boolean panagram = true; 18 | for(int a = 0; a < freqDist.length;a++){ 19 | if(freqDist[a] == 0){ 20 | panagram = false; 21 | } 22 | } 23 | if(panagram){ 24 | System.out.println("pangram"); 25 | } 26 | else{ 27 | System.out.println("not pangram"); 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /ProjectEulerPlus_Problem1.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | import java.text.*; 4 | import java.math.*; 5 | import java.util.regex.*; 6 | /* 7 | This problem is a programming version of Problem 1 from projecteuler.net 8 | 9 | If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. 10 | 11 | Find the sum of all the multiples of 3 or 5 below N. 12 | 13 | Input Format 14 | First line contains T that denotes the number of test cases. This is followed by T lines, each containing an integer, N. 15 | 16 | Output Format 17 | For each test case, print an integer that denotes the sum of all the multiples of 3 or 5 below N. 18 | 19 | Constraints 20 | 1≤T≤105 21 | 1≤N≤109 22 | */ 23 | 24 | public class ProjectEulerPlus_Problem1 { 25 | public static void main(String[] args) { 26 | /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ 27 | Scanner stdin = new Scanner(System.in); 28 | // The first integer is the number of cases to be evaluated. 29 | int numberOfCases = Integer.parseInt(stdin.nextLine()); 30 | // Set initial values 31 | BigInteger sum = new BigInteger("0"); 32 | int caseTemp = 0; 33 | BigInteger temp = null; 34 | //Loop through the number of given cases 35 | for(int a = 0; a < numberOfCases; a++){ 36 | caseTemp = Integer.parseInt(stdin.nextLine()) - 1; 37 | BigInteger caseTemp2 = new BigInteger("" + caseTemp); 38 | //Set sum of the a'th case to zero 39 | sum = new BigInteger("0"); 40 | 41 | //Calculate the number of multiples of 3 under the value given. 42 | temp = caseTemp2.divide(new BigInteger("3")); 43 | 44 | //Sum these multiples using n*(n+1)/2*3 where n is the number of multiples, and add this to the current sum. 45 | sum = sum.add(temp.multiply(temp.add(new BigInteger("1"))).divide(new BigInteger("2")).multiply(new BigInteger("3"))); 46 | 47 | //Calculate the number of multiples of 5 under the value given. 48 | temp = caseTemp2.divide(new BigInteger("5")); 49 | 50 | //Sum these multiples using n*(n+1)/2*5 where n is the number of multiples, and add this to the current sum. 51 | sum = sum.add(temp.multiply(temp.add(new BigInteger("1"))).divide(new BigInteger("2")).multiply(new BigInteger("5"))); 52 | 53 | //At this point, we've solved for each value, but we've double counted multiples of 3 and 5. In order to fix this, we will subtract the sum of all of the multiples of 15 under n. 54 | //Calculate the number of multiples of 15 under the value given. 55 | temp = caseTemp2.divide(new BigInteger("15")); 56 | 57 | //Sum these multiples using n*(n+1)/2*15 where n is the number of multiples, and subtract this from the current sum. 58 | sum = sum.subtract(temp.multiply(temp.add(new BigInteger("1"))).divide(new BigInteger("2")).multiply(new BigInteger("15"))); 59 | 60 | //Print out answer for the given case. 61 | System.out.println(sum); 62 | } 63 | 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /Project_Euler_Plus_Problem12.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /* 4 | * The sequence of triangle numbers is generated by adding the natural numbers. So the 7'th triangle number would be 1+2+3+4+5+6+7=28. The first ten terms would be: 5 | 6 | 1,3,6,10,15,21,28,36,45,55,... 7 | 8 | Let us list the factors of the first seven triangle numbers: 9 | 10 | 1:1 11 | 3:1,3 12 | 6:1,2,3,6 13 | 10:1,2,5,10 14 | 15:1,3,5,15 15 | 21:1,3,7,21 16 | 28:1,2,4,7,14,28 17 | 18 | We can see that 28 is the first triangle number to have over five divisors. 19 | 20 | What is the value of the first triangle number to have over N divisors? 21 | 22 | Input 23 | First line T, the number of testcases. Each testcase consists of N in one line. 24 | 25 | Output 26 | For each testcase, print the required answer in one line. 27 | 28 | Constraints 29 | 1≤T≤10 30 | 1≤N≤103 31 | */ 32 | public class Project_Euler_Plus_Problem12 { 33 | public static void main(String[] args) { 34 | Scanner stdin = new Scanner(System.in); 35 | int numberOfCases = Integer.parseInt(stdin.nextLine()); 36 | //Parse the first line of input, the number of cases. 37 | 38 | int[] preProcessing = preProcess(); 39 | //Pre-process data 40 | 41 | String input; 42 | for (int a = 0; a < numberOfCases; a++) { 43 | input = stdin.nextLine(); 44 | int inputData = Integer.parseInt(input); 45 | System.out.println(preProcessing[inputData+1]); 46 | 47 | } 48 | } 49 | /* 50 | * Calculates the number of divisors for a given number. 51 | * Complexity goes up with the squareroot of the input number. 52 | */ 53 | public static int getNumDivisors(int number){ 54 | int count = 0; 55 | for(int a = 1; a < Math.sqrt(number); a++){ 56 | if (number%a == 0){ 57 | count = count + 2; 58 | //Each factor we find mean that two factors exist, a and number/a, 59 | //with the exception of when a = number/a, which is the squareroot case. 60 | } 61 | } 62 | if (Math.sqrt(number)%1 == 0){ 63 | count++; //Compensating for the square root case 64 | } 65 | return count; 66 | } 67 | /* 68 | * pre-processes the data and populates an array with the lowest triangular number with n factors, where n is the index of the array. 69 | */ 70 | public static int[] preProcess(){ 71 | int[] preProcessing = new int[1002]; 72 | for(int a = 0; a < preProcessing.length; a++){ 73 | preProcessing[a] = 0; 74 | } 75 | 76 | 77 | for(int a = 0; a < preProcessing.length; a++){ 78 | int triangular = 0; 79 | int count = 1; 80 | int temp = 0; 81 | while(preProcessing[1001] == 0){ 82 | triangular += count; 83 | count++; 84 | temp = getNumDivisors(triangular); 85 | if (temp > 1001){ 86 | temp = 1001; 87 | } 88 | if (preProcessing[temp] == 0){ 89 | for(int b = 0; b < temp; b++){ 90 | if (triangular < preProcessing[b] || preProcessing[b] == 0){ 91 | preProcessing[b] = triangular; 92 | } 93 | } 94 | preProcessing[temp] = triangular; 95 | } 96 | } 97 | } 98 | return preProcessing; 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /Project_Euler_Plus_Problem_1.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | import java.text.*; 4 | import java.math.*; 5 | import java.util.regex.*; 6 | //https://www.hackerrank.com/contests/projecteuler/challenges/euler001 7 | /* Problem Statement: 8 | * 9 | * If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. 10 | 11 | Find the sum of all the multiples of 3 or 5 below N. 12 | 13 | Input Format 14 | First line contains T that denotes the number of test cases. This is followed by T lines, each containing an integer, N. 15 | 16 | Output Format 17 | For each test case, print an integer that denotes the sum of all the multiples of 3 or 5 below N. 18 | 19 | Constraints 20 | 1≤T≤105 21 | 1≤N≤109 22 | */ 23 | public class Project_Euler_Plus_Problem_1 { 24 | 25 | public static void main(String[] args) { 26 | /* 27 | * Enter your code here. Read input from STDIN. Print output to STDOUT. 28 | * Your class should be named Solution. 29 | */ 30 | Scanner stdin = new Scanner(System.in); 31 | int numberOfCases = Integer.parseInt(stdin.nextLine()); 32 | BigInteger sum = new BigInteger("0"); 33 | int caseTemp = 0; 34 | BigInteger temp = null; 35 | for (int a = 0; a < numberOfCases; a++) { 36 | caseTemp = Integer.parseInt(stdin.nextLine()) - 1; 37 | BigInteger caseTemp2 = new BigInteger("" + caseTemp); 38 | sum = new BigInteger("0"); 39 | temp = caseTemp2.divide(new BigInteger("3")); 40 | sum = sum.add(temp.multiply(temp.add(new BigInteger("1"))) 41 | .divide(new BigInteger("2")).multiply(new BigInteger("3"))); 42 | temp = caseTemp2.divide(new BigInteger("5")); 43 | sum = sum.add(temp.multiply(temp.add(new BigInteger("1"))) 44 | .divide(new BigInteger("2")).multiply(new BigInteger("5"))); 45 | temp = caseTemp2.divide(new BigInteger("15")); 46 | sum = sum 47 | .subtract(temp.multiply(temp.add(new BigInteger("1"))) 48 | .divide(new BigInteger("2")) 49 | .multiply(new BigInteger("15"))); 50 | System.out.println(sum); 51 | } 52 | 53 | } 54 | } -------------------------------------------------------------------------------- /Project_Euler_Plus_Problem_10.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.Scanner; 3 | 4 | /** 5 | * Problem Statement 6 | * 7 | * This problem is a programming version of Problem 10 from projecteuler.net 8 | * 9 | * The sum of the primes below 10 is 2+3+5+7=17. 10 | * 11 | * Find the sum of all the primes not greater than given N. 12 | * 13 | * Input Format The first line contains an integer T i.e. number of the test 14 | * cases. The next T lines will contains an integer N. 15 | * 16 | * Output Format Print the value corresponding to each test case in seperate 17 | * line. 18 | * 19 | * Constraints 1≤T≤104 1≤N≤106 20 | */ 21 | public class Project_Euler_Plus_Problem_10 { 22 | public static void main(String[] args) { 23 | Scanner stdin = new Scanner(System.in); 24 | int numberOfCases = Integer.parseInt(stdin.nextLine()); // Parse number 25 | // of cases 26 | int[] input = new int[numberOfCases]; 27 | for (int a = 0; a < numberOfCases; a++) { // Import all data 28 | input[a] = stdin.nextInt(); 29 | if (a != numberOfCases - 1) { 30 | stdin.nextLine(); 31 | } 32 | } 33 | 34 | // First, we sort the list of input. After this, we can simply go up 35 | // through numbers, finding primes as we move upward. 36 | int[] sortedInput = input.clone(); 37 | Arrays.sort(sortedInput); 38 | 39 | // Next, we write a method to primeCheck. (see primecheck method) 40 | 41 | long[] nthPrimeNumberArray = new long[sortedInput.length]; 42 | for (int a = 0; a < numberOfCases; a++) { 43 | nthPrimeNumberArray[a] = 0; 44 | } 45 | 46 | for (int a = 2; a <= sortedInput[sortedInput.length - 1]; a++) { 47 | if (primeCheck(a)) { 48 | for (int index = 0; index < sortedInput.length; index++) { 49 | if (a <= sortedInput[index]) { 50 | nthPrimeNumberArray[index] += a; 51 | } 52 | } 53 | } 54 | } 55 | // Now, we have a sorted list of all of the answers. It's a simple task 56 | // to search the array of answers for the correct value. 57 | // If the number of test cases was large, we would use binary search. 58 | 59 | for (int a = 0; a < numberOfCases; a++) { 60 | for (int b = 0; b < numberOfCases; b++) { 61 | if (input[a] == sortedInput[b]) { 62 | System.out.println(nthPrimeNumberArray[b]); 63 | break; 64 | } 65 | } 66 | } 67 | 68 | } 69 | 70 | public static boolean primeCheck(int numberToTest) { 71 | for (int a = 2; a <= Math.sqrt(numberToTest); a++) { 72 | if (numberToTest % a == 0) { 73 | return false; 74 | } 75 | } 76 | return true; 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /Project_Euler_Plus_Problem_11.java: -------------------------------------------------------------------------------- 1 | import java.math.BigInteger; 2 | import java.util.Scanner; 3 | 4 | /* 5 | * Problem Statement 6 | 7 | This problem is a programming version of Problem 11 from projecteuler.net 8 | 9 | In the 20×20 grid below, four numbers along a diagonal line have been marked in bold. 10 | 11 | 89 90 95 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 12 | 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 13 | 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 14 | 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 15 | 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 16 | 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 17 | 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 18 | 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 19 | 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 20 | 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 21 | 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 22 | 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 23 | 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 24 | 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 25 | 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 26 | 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 27 | 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 28 | 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 29 | 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 30 | 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 31 | 32 | The product of these numbers is 26 × 63 × 78 × 14 = 1788696. 33 | 34 | What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20×20 grid? 35 | 36 | Input Format 37 | Input consists of 20 lines each containing 20 integers. 38 | 39 | Output Format 40 | Print the required answer. 41 | 42 | Constraints 43 | 0 ≤ Each integer in the grid ≤ 100 44 | */ 45 | public class Project_Euler_Plus_Problem_11 { 46 | public static void main(String[] args) { 47 | Scanner stdin = new Scanner(System.in); 48 | 49 | int[][] input = new int[20][20]; 50 | for (int a = 0; a < 20; a++) { // grid is 20x20 51 | for (int b = 0; b < 20; b++) { // grid is 20x20 52 | input[a][b] = stdin.nextInt(); // Parse input data 53 | } 54 | if (a != 19) { 55 | stdin.nextLine(); 56 | } 57 | } 58 | 59 | /*for (int a = 0; a < 20; a++) { // grid is 20x20 60 | for (int b = 0; b < 20; b++) { // grid is 20x20 61 | System.out.print(input[a][b] 62 | + ((input[a][b] < 10) ? " : " : " : ")); 63 | } 64 | System.out.println(""); 65 | } 66 | */ 67 | int max = 0; 68 | int product; 69 | // We must check horizontally, vertically, and diagonally. 70 | for (int b = 1; b < 20; b++) {// Check vertically. 71 | // First, we enter the first 4. 72 | product = input[0][b] * input[1][b] * input[2][b] * input[3][b]; 73 | 74 | if (max < product) { 75 | max = product; 76 | } 77 | 78 | for (int a = 1; a < 17; a++) { 79 | // Now, we can multiply the 5th number down, and divide by the 80 | // top number. This divides the number of numbers we must 81 | // multiply by a factor of 2. 82 | // (2 operations compared to 4 multiplications) 83 | if (input[a - 1][b] == 0) { 84 | product = input[a][b] * input[a + 1][b] * input[a + 2][b]; 85 | // Check for dividing by zero. 86 | } else { 87 | product /= input[a - 1][b]; 88 | } 89 | product *= input[a + 3][b]; 90 | if (max < product) { 91 | max = product; // update max if necessary 92 | } 93 | } 94 | } 95 | 96 | for (int a = 0; a < 20; a++) { // Check horizontally (using the same 97 | // method as above). 98 | product = input[a][0] * input[a][1] * input[a][2] * input[a][3]; 99 | // Solve for the initial product 100 | if (max < product) { 101 | max = product; // update max if necessary 102 | } 103 | 104 | for (int b = 1; b < 17; b++) { 105 | if (input[a][b - 1] == 0) { 106 | product = input[a][b] * input[a][b + 1] * input[a][b + 2]; 107 | } else { 108 | product /= input[a][b - 1]; 109 | } 110 | product *= input[a][b + 3]; 111 | if (max < product) { 112 | max = product; // update max if necessary 113 | } 114 | } 115 | } 116 | 117 | for (int a = 0; a < 17; a++) { // Check diagonally in the down-right 118 | // direction. 119 | // This is tricky, because if we go diagonally, across the matrix 120 | // for efficiency, it's a pain to keep track of how far we have to 121 | // go for each row. 122 | // It is only a few more operations to just multiply over each one, 123 | // so we'll go ahead and do it. 124 | for (int b = 0; b < 17; b++) { 125 | product = input[a][b] * input[a + 1][b + 1] 126 | * input[a + 2][b + 2] * input[a + 3][b + 3]; 127 | if (max < product) { 128 | max = product; // update max if necessary 129 | } 130 | } 131 | } 132 | 133 | for (int a = 0; a < 17; a++) { // Check diagonally in the down-left 134 | // direction. 135 | for (int b = 3; b < 20; b++) { 136 | product = input[a][b] * input[a + 1][b - 1] 137 | * input[a + 2][b - 2] * input[a + 3][b - 3]; 138 | if (max < product) { 139 | max = product; // update max if necessary 140 | } 141 | } 142 | } 143 | 144 | System.out.println(max); 145 | 146 | } 147 | 148 | } 149 | -------------------------------------------------------------------------------- /Project_Euler_Plus_Problem_13.java: -------------------------------------------------------------------------------- 1 | import java.math.BigInteger; 2 | import java.util.Scanner; 3 | 4 | /* 5 | * Problem Statement 6 | 7 | This problem is a programming version of Problem 13 from projecteuler.net 8 | 9 | Work out the first ten digits of the sum of N 50-digit numbers. 10 | 11 | Input Format 12 | First line contains N, next N lines contain a 50 digit number each. 13 | 14 | Output Format 15 | Print only first 10 digit of the final sum 16 | 17 | Constraints 18 | 1≤N≤103 19 | 20 | Sample Input 21 | 22 | 5 23 | 37107287533902102798797998220837590246510135740250 24 | 46376937677490009712648124896970078050417018260538 25 | 74324986199524741059474233309513058123726617309629 26 | 91942213363574161572522430563301811072406154908250 27 | 23067588207539346171171980310421047513778063246676 28 | Sample Output 29 | 30 | 2728190129 31 | */ 32 | public class Project_Euler_Plus_Problem_13 { 33 | 34 | public static void main(String[] args) { 35 | Scanner stdin = new Scanner(System.in); 36 | int numberOfCases = Integer.parseInt(stdin.nextLine()); 37 | String input; 38 | BigInteger sum = new BigInteger("0"); 39 | for (int a = 0; a < numberOfCases; a++) { 40 | input = stdin.nextLine(); 41 | sum = sum.add(new BigInteger(input)); 42 | } 43 | String answer = sum.toString(); 44 | System.out.println(answer.substring(0, 10)); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /Project_Euler_Plus_Problem_14.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | import java.util.*; 3 | 4 | public class Project_Euler_Plus_Problem_14 { 5 | /* 6 | * Problem Statement 7 | 8 | This problem is a programming version of Problem 14 from projecteuler.net 9 | 10 | The following iterative sequence is defined for the set of positive integers: 11 | 12 | nn→n2→3n+1 n is even n is odd 13 | Using the rule above and starting with 13, we generate the following sequence: 14 | 15 | 13→40→20→10→5→16→8→4→2→1 16 | It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. 17 | 18 | Which starting number, ≤N produces the longest chain? If many possible such numbers are there print the maximum one. 19 | 20 | Note: Once the chain starts the terms are allowed to go above N. 21 | 22 | Input Format 23 | The first line contains an integer T , i.e., number of test cases. 24 | Next T lines will contain an integers N. 25 | 26 | Output Format 27 | Print the values corresponding to each test case. 28 | 29 | Constraints 30 | 1 ≤ T ≤ 10^4 31 | 1 ≤ N ≤ 5*10^6 32 | */ 33 | public static void main(String[] args) { 34 | Scanner stdin = new Scanner(System.in); 35 | int numberOfCases = Integer.parseInt(stdin.nextLine()); 36 | ArrayList preProcess = preProcessing(); 37 | 38 | String input; 39 | for (int a = 0; a < numberOfCases; a++) { 40 | input = stdin.nextLine(); 41 | int inputInt = Integer.parseInt(input); 42 | long index2 = inputInt; 43 | System.out.println(preProcess.get((int) index2)); 44 | 45 | } 46 | } 47 | 48 | public static ArrayList preProcessing() { 49 | ArrayList length = new ArrayList(200000); 50 | ArrayList maxIndexes = new ArrayList(200000); 51 | length.add(0, 0); 52 | maxIndexes.add(0); 53 | int max = 0; 54 | int maxIndex = 1; 55 | for (int a = 1; a < 100000; a++) { 56 | int temp = getLength(a, length); // / 57 | length.add(a, temp); 58 | if (max <= temp) { 59 | max = temp; 60 | maxIndex = (int) a; 61 | } 62 | maxIndexes.add(a, maxIndex); 63 | } 64 | return maxIndexes; 65 | } 66 | 67 | public static int getLength(int b, ArrayList length) { 68 | int count = 0; 69 | int a = b; 70 | ArrayList trail = new ArrayList(); 71 | while (a != 1) { 72 | trail.add((long) a); 73 | if (a % 2 == 0) { 74 | a = a / 2; 75 | count++; 76 | } else { 77 | a = 3 * a + 1; 78 | count++; 79 | } 80 | if (a > 0 && a < 2147000000 && a <= length.size()) { 81 | if (length.get((int) a) != null) { 82 | count = count + length.get((int) a); 83 | a = 1; 84 | } 85 | } 86 | } 87 | for (int d = 0; d < trail.size(); d++) { 88 | if (trail.get(d) < 2147000000 89 | && ((int) (long) trail.get(d)) < length.size() 90 | && length.get((int) (long) trail.get(d)) == null) { 91 | length.add((int) (long) trail.get(d), count - d); 92 | // System.out.println(trail.get(d) + " " + (count-d)); 93 | } 94 | } 95 | return count; 96 | 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /Project_Euler_Plus_Problem_14b.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | import java.util.*; 3 | 4 | public class Project_Euler_Plus_Problem_14b { 5 | /* 6 | * Problem Statement 7 | 8 | This problem is a programming version of Problem 14 from projecteuler.net 9 | 10 | The following iterative sequence is defined for the set of positive integers: 11 | 12 | nn→n2→3n+1 n is even n is odd 13 | Using the rule above and starting with 13, we generate the following sequence: 14 | 15 | 13→40→20→10→5→16→8→4→2→1 16 | It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. 17 | 18 | Which starting number, ≤N produces the longest chain? If many possible such numbers are there print the maximum one. 19 | 20 | Note: Once the chain starts the terms are allowed to go above N. 21 | 22 | Input Format 23 | The first line contains an integer T , i.e., number of test cases. 24 | Next T lines will contain an integers N. 25 | 26 | Output Format 27 | Print the values corresponding to each test case. 28 | 29 | Constraints 30 | 1 ≤ T ≤ 10^4 31 | 1 ≤ N ≤ 5*10^6 32 | */ 33 | 34 | public static void main(String[] args) { 35 | Scanner stdin = new Scanner(System.in); 36 | int numberOfCases = Integer.parseInt(stdin.nextLine()); 37 | HashMap preProcess = preProcessing(); 38 | String input; 39 | for (int a = 0; a < numberOfCases; a++) { 40 | input = stdin.nextLine(); 41 | int inputInt = Integer.parseInt(input); 42 | 43 | int max = 0; 44 | int index = 0; 45 | long index2 = -1 * inputInt; 46 | if (index2 < -250000){ 47 | index2 = -250000; 48 | } 49 | while(!preProcess.containsKey(index2)){ 50 | index2++; 51 | //System.out.println(index2); 52 | } 53 | System.out.println(preProcess.get(index2)); 54 | 55 | } 56 | } 57 | public static HashMap preProcessing(){ 58 | HashMap preprocess = new HashMap(500000); 59 | int max = 0; 60 | int maxIndex = 0; 61 | for(long a = 1; a < 250000; a++){ 62 | int temp = getLength(a, preprocess); 63 | preprocess.put(a, temp); 64 | if (max <= temp ){ 65 | //System.out.println((a * -1) + " " + getLength(a, preprocess)); 66 | preprocess.put(a * -1, (int) a ); 67 | max = temp; 68 | maxIndex = (int) a; 69 | } 70 | else preprocess.put(a*-1, maxIndex); 71 | } 72 | return preprocess; 73 | } 74 | public static int getLength(long b, HashMap c){ 75 | int count = 0; 76 | long a = b; 77 | ArrayList trail = new ArrayList(); 78 | while (a != 1){ 79 | trail.add(a); 80 | if(a%2 == 0){ 81 | a = a/2; 82 | count++; 83 | } 84 | else{ 85 | a = 3 * a + 1; 86 | count++; 87 | } 88 | if (c.containsKey(a)){ 89 | count = count + c.get(a); 90 | a = 1; 91 | } 92 | } 93 | for(int d = 0; d < trail.size(); d++){ 94 | if(!c.containsKey(trail.get(d))){ 95 | c.put(trail.get(d), count-d); 96 | //System.out.println(trail.get(d) + " " + (count-d)); 97 | } 98 | } 99 | return count; 100 | 101 | } 102 | } 103 | 104 | 105 | 106 | -------------------------------------------------------------------------------- /Project_Euler_Plus_Problem_15.java: -------------------------------------------------------------------------------- 1 | import java.math.BigInteger; 2 | import java.util.Scanner; 3 | 4 | public class Project_Euler_Plus_Problem_15 { 5 | public static void main(String[] args) { 6 | int[][] cache1 = new int[501][501]; 7 | Scanner stdin = new Scanner(System.in); 8 | int numberOfCases = Integer.parseInt(stdin.nextLine()); 9 | 10 | for (int a = 0; a < numberOfCases; a++) { 11 | int n = stdin.nextInt(); 12 | int m = stdin.nextInt(); 13 | if( a != numberOfCases-1){ 14 | stdin.nextLine(); 15 | } 16 | System.out.println(solve(n, m, cache1)); 17 | } 18 | } 19 | public static int solve(int n, int m, int[][] cache){ 20 | if((m == 0) || (n == 0)){ 21 | return 1; 22 | } 23 | int left = (((cache[n-1][m] != 0) ? cache[n-1][m] : solve(n-1, m, cache))); 24 | int right = (((cache[n][m-1] != 0) ? cache[n][m-1] : solve(n, m-1, cache))); 25 | cache[n][m] = (left + right)%1000000007; 26 | return cache[n][m]; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Project_Euler_Plus_Problem_16.java: -------------------------------------------------------------------------------- 1 | import java.math.BigInteger; 2 | import java.util.Scanner; 3 | /* 4 | * Problem 5 | Submissions 6 | Leaderboard 7 | Discussions 8 | Problem Statement 9 | 10 | This problem is a programming version of Problem 16 from projecteuler.net 11 | 12 | 29=512 and the sum of its digits is 5+1+2=8. 13 | 14 | What is the sum of the digits of the number 2N ? 15 | 16 | Input Format 17 | The first line contains an integer T , i.e., number of test cases. 18 | Next T lines will contain an integer N. 19 | 20 | Output Format 21 | Print the values corresponding to each test case. 22 | 23 | Constraints 24 | 1≤T≤100 25 | 1≤N≤10^4 26 | 27 | Sample Input 28 | 29 | 3 30 | 3 31 | 4 32 | 7 33 | Sample Output 34 | 35 | 8 36 | 7 37 | 11 38 | */ 39 | 40 | 41 | public class Project_Euler_Plus_Problem_16 { 42 | public static void main(String[] args) { 43 | Scanner stdin = new Scanner(System.in); 44 | int numberOfCases = Integer.parseInt(stdin.nextLine()); 45 | String input; 46 | for (int a = 0; a < numberOfCases; a++) { 47 | input = stdin.nextLine(); 48 | int inputInt = Integer.parseInt(input); 49 | BigInteger b = (new BigInteger("2")).pow(inputInt); 50 | String stringOfCharacters = b.toString(); 51 | char[] numericValues = stringOfCharacters.toCharArray(); 52 | int sum = 0; 53 | for(int c = 0; c < numericValues.length; c++){ 54 | sum += Integer.parseInt("" + numericValues[c]); 55 | } 56 | System.out.println(sum); 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /Project_Euler_Plus_Problem_18.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | /* 3 | * Problem Statement 4 | 5 | This problem is a programming version of Problem 18 from projecteuler.net 6 | 7 | By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23. The path is denoted by numbers in bold. 8 | 9 | 3 10 | 74 11 | 246 12 | 8593 13 | 14 | That is, 3+7+4+9=23. 15 | 16 | Find the maximum total from top to bottom of the triangle given in input. 17 | 18 | Input 19 | First line contains T, the number of testcases. For each testcase: 20 | First line contains N, the number of rows in the triangle. 21 | For next N lines, i'th line contains i numbers. 22 | 23 | Output 24 | For each testcase, print the required answer in a newline. 25 | 26 | Constraints 27 | 1≤T≤10 28 | 1≤N≤15 29 | numbers∈[0,100) 30 | */ 31 | public class Project_Euler_Plus_Problem_18 { 32 | public static void main(String[] args) { 33 | Scanner stdin = new Scanner(System.in); 34 | int numberOfCases = Integer.parseInt(stdin.nextLine()); 35 | String input; 36 | for (int a = 0; a < numberOfCases; a++) { 37 | int b = stdin.nextInt(); 38 | int[][] inputArray = new int[b][b]; 39 | for(int c = 0; c < b; c++){ 40 | for(int d = 0; d <= c; d++){ 41 | inputArray[c][d] = stdin.nextInt(); 42 | } 43 | } 44 | int max = 0; 45 | int count = 0; 46 | int sum = 0; 47 | int index = 0; 48 | while(count < Math.pow(2, b)){ 49 | sum = 0; 50 | index = 0; 51 | for(int c = 0; c < b; c++){ 52 | sum += inputArray[c][index]; 53 | int d = (int) (count / Math.pow(2, c)); 54 | d = d%2; 55 | index += d; 56 | } 57 | if(max < sum){ 58 | max = sum; 59 | } 60 | count++; 61 | } 62 | System.out.println(max); 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /Project_Euler_Plus_Problem_2.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | import java.io.*; 3 | import java.util.*; 4 | import java.text.*; 5 | import java.math.*; 6 | import java.util.regex.*; 7 | 8 | public class Project_Euler_Plus_Problem_2 { 9 | /* 10 | * Problem Statement: 11 | * Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 12 | 1,2,3,5,8,13,21,34,55,89,⋯ 13 | By considering the terms in the Fibonacci sequence whose values do not exceed N, find the sum of the even-valued terms. 14 | 15 | Input Format 16 | First line contains T that denotes the number of test cases. This is followed by T lines, each containing an integer, N. 17 | 18 | Output Format 19 | Print the required answer for each test case. 20 | 21 | Constraints 22 | 1≤T≤10^5 23 | 10≤N≤4×10^16 24 | */ 25 | public static void main(String[] args) { 26 | Scanner stdin = new Scanner(System.in); 27 | 28 | //Parse number of test cases. 29 | int numberOfCases = Integer.parseInt(stdin.nextLine()); 30 | 31 | //Create an array of Fibonacci up to 4x10^16. We don't know exactly how large to make this array, but we can safely establish that it is smaller than 2 * log2(4x10^16) by using inequalities. 32 | // 1 2 3 5 8 13 .... is guaranteed to be greater than the following sequence, and therefore will reach 4x10^16 faster. 33 | // 1 1 2 2 4 4 8 8... (Proof; Term1top = Term1bottom, Term2top>Term2bottom. Term 1 + Term 2 > Term1 * 2. Continue this process, all upper terms are greater or equal to lower terms. 34 | //Therefore, 2 * log2(4x10^16) is large enough. 35 | //10^3 < 2^10, so 2 * log2(2^58) > 2 * log2(4x10^16), and our array can safely be size 116. 36 | 37 | BigInteger[] fibonacci = new BigInteger[116]; 38 | BigInteger endpoint = new BigInteger("40000000000000000"); 39 | BigInteger number1 = new BigInteger("1"); 40 | BigInteger number2 = new BigInteger("2"); 41 | fibonacci[0] = number1; 42 | fibonacci[1] = number2; 43 | int index = 2; 44 | while (number2.compareTo(endpoint) < 0){ //We'll go two at a time for simplicity. 45 | number1 = number2.add(number1); 46 | fibonacci[index] = number1; 47 | index++; 48 | number2 = number1.add(number2); 49 | fibonacci[index] = number2; 50 | index++; 51 | } 52 | 53 | 54 | 55 | //We're safe! The array only needed to be 82 integers long. 56 | //Now that we have made this array, the rest of the problem is pretty easy. Our next step is to make another array, that contains the sum of the even numbered values up to a given index. 57 | BigInteger[] fibonacciEvenSums = new BigInteger[116]; 58 | 59 | BigInteger sum = new BigInteger("" + 0); 60 | int index2 = 0; 61 | for(int a = 0; a < 82; a++){ 62 | if (fibonacci[a].mod(new BigInteger(2 + "")).compareTo(new BigInteger(0 + "")) < 1){ 63 | sum = sum.add(fibonacci[a]); 64 | } 65 | 66 | fibonacciEvenSums[a] = sum; 67 | System.out.println(fibonacci[a] + " " + fibonacciEvenSums[a]); 68 | index2++; 69 | } 70 | 71 | 72 | 73 | 74 | 75 | // Now, it's a matter of taking the input, finding which is the closest fibonacci element without going over, and printing the desired result. 76 | // Note: This would be slightly more efficient with a binary search; There is only 80 elements however, so there is not a massive benefit of doing so. 77 | int index3; 78 | BigInteger input; 79 | for(int a = 0; a < numberOfCases; a++){ 80 | index3 = 0; 81 | input = new BigInteger(stdin.nextLine()); 82 | while(input.compareTo(fibonacci[index3]) >= 0){ 83 | index3++; 84 | } 85 | System.out.println(fibonacciEvenSums[index3-1]); 86 | } 87 | 88 | 89 | 90 | } 91 | 92 | } 93 | -------------------------------------------------------------------------------- /Project_Euler_Plus_Problem_3.java: -------------------------------------------------------------------------------- 1 | import java.math.BigInteger; 2 | import java.util.Scanner; 3 | import java.util.ArrayList; 4 | /* 5 | * Problem Statement 6 | 7 | This problem is a programming version of Problem 3 from projecteuler.net 8 | 9 | The prime factors of 13195 are 5, 7, 13 and 29. 10 | 11 | What is the largest prime factor of a given number N? 12 | 13 | Input Format 14 | First line contains T, the number of test cases. This is followed by T lines each containing an integer N. 15 | 16 | Output Format 17 | For each test case, display the largest prime factor of N. 18 | 19 | Constraints 20 | 1≤T≤10 21 | 10≤N≤10^12 22 | */ 23 | public class Project_Euler_Plus_Problem_3 { 24 | 25 | public static void main(String[] args) { 26 | Scanner stdin = new Scanner(System.in); 27 | 28 | //Parse the number of cases 29 | int numberOfCases = Integer.parseInt(stdin.nextLine()); 30 | Long input; 31 | 32 | //If there was a large number of test cases, we would maintain an arrayList of prime numbers to save computation time. Because there are only ten, we shouldn't. 33 | //The code commented out is what I would do with a larger test case, although I'd avoid repeats in my prime list. 34 | //Note: We only have to check up to the square root, because if we havn't found a factor below the square root of a number the number must be prime! 35 | 36 | /* 37 | ArrayList listOfPrimes = new ArrayList(10000); //Starting that arraylist off fairly large to increase speed. 38 | boolean isPrime = true; 39 | long max = -1; 40 | for (int a = 0; a < numberOfCases; a++) { 41 | input = new Long(stdin.nextLine()); 42 | for(long b = 2; b <= Math.sqrt(input); b++){ 43 | isPrime = true; 44 | for(long primeCheck : listOfPrimes){ 45 | if (b % primeCheck == 0){ 46 | isPrime = false; 47 | break; 48 | } 49 | } 50 | if (isPrime){ 51 | listOfPrimes.add(b); 52 | } 53 | if (isPrime && input % b == 0){ 54 | max = b; 55 | input /= b; 56 | b--; 57 | } 58 | } 59 | System.out.println(Math.max(input, max)); 60 | } 61 | */ 62 | 63 | long max = -1; 64 | for (int a = 0; a < numberOfCases; a++) { 65 | input = new Long(stdin.nextLine()); 66 | for(long b = 2; b <= Math.sqrt(input); b++){ 67 | if (input % b == 0){ 68 | max = b; 69 | input /= b; 70 | b--; 71 | } 72 | } 73 | System.out.println(Math.max(input, max)); 74 | } 75 | } 76 | } 77 | 78 | 79 | -------------------------------------------------------------------------------- /Project_Euler_Plus_Problem_4.java: -------------------------------------------------------------------------------- 1 | import java.math.BigInteger; 2 | import java.util.Arrays; 3 | import java.util.Scanner; 4 | 5 | public class Project_Euler_Plus_Problem_4 { 6 | /* 7 | * This problem is a programming version of Problem 4 from projecteuler.net 8 | 9 | A palindromic number reads the same both ways. The smallest 6 digit palindrome made from the product of two 3-digit numbers is 101101=143×707. 10 | 11 | Find the largest palindrome made from the product of two 3-digit numbers which is less than N. 12 | 13 | Input Format 14 | First line contains T that denotes the number of test cases. This is followed by T lines, each containing an integer, N. 15 | 16 | Output Format 17 | Print the required answer for each test case in a new line. 18 | 19 | Constraints 20 | 1≤T≤100 21 | 101101 100000){ 40 | if(isPalindrome(number1*number2 + "")){ 41 | for(int a = 0; a < sortedInput.length; a++){ 42 | if (maxPalindrome[a] < number1*number2 && number1*number2 < sortedInput[a]) 43 | maxPalindrome[a] = number1 * number2; 44 | } 45 | 46 | } 47 | } 48 | } 49 | } 50 | 51 | int[] answers = new int[numberOfCases]; 52 | int index = 0; 53 | for(int a = 0; a < numberOfCases; a++){ 54 | for(int b = 0; b< numberOfCases; b++){ 55 | if (input[a] == sortedInput[b]){ 56 | index = b; 57 | break; 58 | } 59 | } 60 | answers[a] = maxPalindrome[index]; 61 | } 62 | 63 | for(int a = 0; a < numberOfCases; a++){ 64 | System.out.println(answers[a]); 65 | } 66 | 67 | } 68 | public static boolean isPalindrome(String input){ 69 | for(int a = 0; a < input.length()/2; a++){ 70 | if (input.charAt(a) != input.charAt(input.length()-a-1)){ 71 | return false; 72 | } 73 | } 74 | return true; 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /Project_Euler_Plus_Problem_5.java: -------------------------------------------------------------------------------- 1 | import java.math.BigInteger; 2 | import java.util.ArrayList; 3 | import java.util.Scanner; 4 | 5 | public class Project_Euler_Plus_Problem_5 { 6 | /* 7 | * This problem is a programming version of Problem 5 from projecteuler.net 8 | 9 | 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. 10 | What is the smallest positive number that is evenly divisible(divisible with no remainder) by all of the numbers from 1 to N? 11 | 12 | Input Format 13 | First line contains T that denotes the number of test cases. This is followed by T lines, each containing an integer, N. 14 | 15 | Output Format 16 | Print the required answer for each test case. 17 | 18 | Constraints 19 | 1≤T≤10 20 | 1≤N≤40 21 | * 22 | * 23 | * 24 | */ 25 | public static void main(String[] args) { 26 | Scanner stdin = new Scanner(System.in); 27 | int numberOfCases = Integer.parseInt(stdin.nextLine()); 28 | int input; 29 | ArrayList> factors = new ArrayList>(40); 30 | ArrayList temp = new ArrayList(); 31 | for(int a = 1; a < 41; a++){ 32 | temp.clear(); 33 | int number = a; 34 | int start = 2; 35 | while (number != 1){ 36 | if (number%start == 0){ 37 | temp.add(start); 38 | number/=start; 39 | start--; 40 | } 41 | start++; 42 | } 43 | factors.add((ArrayList) temp.clone()); 44 | } 45 | /* 46 | for(ArrayList a: factors){ 47 | for(int b: a){ 48 | System.out.print(b); 49 | } 50 | System.out.println(""); 51 | } 52 | */ 53 | 54 | int answer = 1; 55 | for (int a = 0; a < numberOfCases; a++) { 56 | input = stdin.nextInt(); 57 | int[] numberOfNumbers = new int[40]; 58 | for(int b = 0; b < numberOfNumbers.length; b++){ 59 | numberOfNumbers[b] = 0; 60 | } 61 | //All non-prime indexes will be blank. 62 | //This list will hold the frequency of each prime factor. 63 | if (a != numberOfCases-1){ 64 | stdin.nextLine(); 65 | } 66 | for(int b = 1; b < input; b++){ 67 | for(int c = 0; c < 40; c++){ 68 | int total = 0; 69 | for(int d : factors.get(b)){ 70 | if (d == c){ 71 | total++; 72 | } 73 | } 74 | if (total > numberOfNumbers[c]){ 75 | numberOfNumbers[c] = total; 76 | } 77 | } 78 | } 79 | answer = 1; 80 | for(int b = 1; b < numberOfNumbers.length; b++){ 81 | if (numberOfNumbers[b] != 0){ 82 | numberOfNumbers[b]--; 83 | answer *= b; 84 | b--; 85 | } 86 | } 87 | System.out.println(answer); 88 | } 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /Project_Euler_Plus_Problem_6.java: -------------------------------------------------------------------------------- 1 | import java.math.BigInteger; 2 | import java.util.Scanner; 3 | 4 | /* 5 | * Problem Statement 6 | 7 | This problem is a programming version of Problem 6 from projecteuler.net 8 | 9 | The sum of the squares of the first ten natural numbers is, 12+22+...+102=385. The square of the sum of the first ten natural numbers is, (1+2+⋯+10)2=552=3025. Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025−385=2640. 10 | 11 | Find the difference between the sum of the squares of the first N natural numbers and the square of the sum. 12 | 13 | Input Format 14 | First line contains T that denotes the number of test cases. This is followed by T lines, each containing an integer, N. 15 | 16 | Output Format 17 | Print the required answer for each test case. 18 | 19 | Constraints 20 | 1≤T≤10^4 21 | 1≤N≤10^4 22 | */ 23 | public class Project_Euler_Plus_Problem_6 { 24 | public static void main(String[] args) { 25 | Scanner stdin = new Scanner(System.in); 26 | int numberOfCases = Integer.parseInt(stdin.nextLine()); 27 | BigInteger input = new BigInteger("0"); 28 | for (int a = 0; a < numberOfCases; a++) { 29 | input = new BigInteger("" + stdin.nextInt()); 30 | if( a != numberOfCases - 1){ 31 | stdin.nextLine(); 32 | } 33 | BigInteger sumOfSquares = input.pow((int) 3).divide(new BigInteger("3")).add(input.pow((int) 2).divide(new BigInteger("2")).add(input.pow((int) 1).divide(new BigInteger("6")))); 34 | BigInteger squareOfSum = (input.multiply(input.add(new BigInteger("1")))).pow(2).divide(new BigInteger("4")); 35 | 36 | BigInteger roundedOffAnswer = squareOfSum.subtract(sumOfSquares); 37 | //Compensating for rounding error by using bigInteger remainders 38 | BigInteger remaindersCubed = (input.pow((int) 3).remainder(new BigInteger("3"))).multiply(new BigInteger("2")); 39 | BigInteger remaindersSquared = (input.pow((int) 2).remainder(new BigInteger("2"))).multiply(new BigInteger("3"));; 40 | BigInteger remainders = (input.pow((int) 1).remainder(new BigInteger("6"))); 41 | BigInteger answer = roundedOffAnswer.subtract(remaindersCubed.add(remaindersSquared.add(remainders)).divide(new BigInteger("6"))); 42 | System.out.println(answer); 43 | } 44 | } 45 | } 46 | //Sum of squares formula n^3/3 + n^2/2 + n/6 47 | -------------------------------------------------------------------------------- /Project_Euler_Plus_Problem_7.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.Scanner; 3 | 4 | /** 5 | * Problem Statement 6 | 7 | This problem is a programming version of Problem 7 from projecteuler.net 8 | 9 | By listing the first six prime numbers: 2,3,5,7,11 and 13, we can see that the 6th prime is 13. 10 | What is the N'th prime number? 11 | 12 | Input Format 13 | First line contains T that denotes the number of test cases. This is followed by T lines, each containing an integer, N. 14 | 15 | Output Format 16 | Print the required answer for each test case. 17 | 18 | Constraints 19 | 1≤T≤10^3 20 | 1≤N≤10^4 21 | 22 | */ 23 | public class Project_Euler_Plus_Problem_7 { 24 | public static void main(String[] args) { 25 | Scanner stdin = new Scanner(System.in); 26 | int numberOfCases = Integer.parseInt(stdin.nextLine()); //Parse number of cases 27 | int[] input = new int[numberOfCases]; 28 | for (int a = 0; a < numberOfCases; a++) { //Import all data 29 | input[a] = stdin.nextInt(); 30 | if (a != numberOfCases - 1){ 31 | stdin.nextLine(); 32 | } 33 | } 34 | 35 | 36 | //First, we sort the list of input. After this, we can simply go up through numbers, finding primes as we move upward. 37 | int[] sortedInput = input.clone(); 38 | Arrays.sort(sortedInput); 39 | 40 | //Next, we write a method to primeCheck. 41 | 42 | int[] nthPrimeNumberArray = new int[sortedInput.length]; 43 | 44 | int index = 0; 45 | int primeCounter = 0; 46 | for(int a = 2; primeCounter < sortedInput[sortedInput.length-1] && index < sortedInput.length; a++){ 47 | if (primeCheck(a)){ 48 | primeCounter++; 49 | if (primeCounter == sortedInput[index]){ 50 | nthPrimeNumberArray[index] = a; 51 | index++; 52 | primeCounter--; 53 | a--; 54 | } 55 | } 56 | } 57 | //Now, we have a sorted list of all of the answers. It's a simple task to search the array of answers for the correct value. 58 | //If the number of test cases was large, we would use binary search. 59 | 60 | for(int a = 0; a < numberOfCases; a++){ 61 | for(int b = 0; b < numberOfCases; b++){ 62 | if (input[a] == sortedInput[b]){ 63 | System.out.println(nthPrimeNumberArray[b]); 64 | break; 65 | } 66 | } 67 | } 68 | 69 | 70 | 71 | 72 | } 73 | public static boolean primeCheck(int numberToTest){ 74 | for(int a = 2; a <= Math.sqrt(numberToTest); a++){ 75 | if (numberToTest % a == 0){ 76 | return false; 77 | } 78 | } 79 | return true; 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /Project_Euler_Plus_Problem_8.java: -------------------------------------------------------------------------------- 1 | import java.math.BigInteger; 2 | import java.util.Scanner; 3 | /* 4 | * Problem Statement 5 | 6 | This problem is a programming version of Problem 8 from projecteuler.net 7 | 8 | Find the greatest product of K consecutive digits in the N digit number. 9 | 10 | Input Format 11 | First line contains T that denotes the number of test cases. 12 | First line of each test case will contain two integers N & K. 13 | Second line of each test case will contain a N digit integer. 14 | 15 | Output Format 16 | Print the required answer for each test case. 17 | 18 | Constraints 19 | 1≤T≤100 20 | 1≤K≤7 21 | K≤N≤1000 22 | */ 23 | public class Project_Euler_Plus_Problem_8 { 24 | public static void main(String[] args) { 25 | //My methodology for my solution is to iterate throught the string, multiplying by the next value and dividing by the value that would no longer be included. 26 | // Example for 5 2 as input. * = product, 0 = unused numbers. 27 | // **000 28 | // 0**00 29 | // 00**0 30 | // 000** 31 | // This results in our solution being 0(N) instead of being O(N*k). 32 | 33 | Scanner stdin = new Scanner(System.in); 34 | int numberOfCases = Integer.parseInt(stdin.nextLine()); 35 | int n; 36 | int k; 37 | String input; 38 | for (int a = 0; a < numberOfCases; a++) { 39 | n = stdin.nextInt(); 40 | k = stdin.nextInt(); 41 | stdin.nextLine(); 42 | input = stdin.nextLine(); 43 | 44 | int max = 0; 45 | int current = 1; 46 | for(int b = 0; b < k; b++){ 47 | current *= Integer.parseInt("" + input.charAt(b)); 48 | } 49 | max = current; 50 | 51 | for(int b = 1; b < n-k; b++){ 52 | if(Integer.parseInt("" + input.charAt(b-1)) != 0){ 53 | current /= Integer.parseInt("" + input.charAt(b-1)); 54 | } 55 | else{ 56 | current = 1; 57 | for(int c = 0; c < k-1; c++){ 58 | current *= Integer.parseInt("" + input.charAt(c + b)); 59 | } 60 | } 61 | current *= Integer.parseInt("" + input.charAt(b+k -1)); 62 | if (current > max){ 63 | max = current; 64 | } 65 | } 66 | System.out.println(max); 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /Project_Euler_Plus_Problem_9.java: -------------------------------------------------------------------------------- 1 | import java.math.BigInteger; 2 | import java.util.Scanner; 3 | /* 4 | * Problem Statement 5 | 6 | This problem is a programming version of Problem 9 from projecteuler.net 7 | 8 | A Pythagorean triplet is a set of three natural numbers, a max){ 50 | max = c * d * b; 51 | } 52 | //b is hypotenuse 53 | //c,d are legs 54 | 55 | } 56 | } 57 | System.out.println(max); 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # HackerRankProblems 2 | HackerRank Solutions that I've written. 3 | This repository is a collection of solutions to HackerRank problems that I've worked on. 4 | -------------------------------------------------------------------------------- /SherlockAndAnagrams.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | //https://www.hackerrank.com/challenges/sherlock-and-anagrams 4 | public class SherlockAndAnagrams { 5 | 6 | public static void main(String[] args) { 7 | // TODO Auto-generated method stub 8 | Scanner input = new Scanner(System.in); 9 | int cases = input.nextInt(); 10 | for (int a = 0; a < cases; a++) { 11 | String sc = input.next(); 12 | int total = 0; 13 | for (int start = 0; start < sc.length(); start++) { 14 | for (int start2 = start + 1; start2 < sc.length(); start2++) { 15 | for (int length = 1; length < sc.length() - Math.max(start2, start) + 1; length++) { 16 | if (isAnagram(sc.substring(start2, start2 + length),(sc.substring(start, start + length)))) { 17 | total++; 18 | } 19 | } 20 | } 21 | } 22 | System.out.println(total); 23 | } 24 | } 25 | 26 | private static boolean isAnagram(String string1, String string2) { 27 | int[] freqDist = new int[26]; 28 | for (int a = 0; a < string1.length(); a++) { 29 | freqDist[string1.charAt(a) - 'a']++; 30 | } 31 | for (int b = 0; b < string2.length(); b++) { 32 | freqDist[string2.charAt(b) - 'a']--; 33 | } 34 | for (int c = 0; c < 26; c++) { 35 | if (freqDist[c] != 0) { 36 | return false; 37 | } 38 | } 39 | return true; 40 | } 41 | 42 | } -------------------------------------------------------------------------------- /SherlockAndTheBeast.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | //https://www.hackerrank.com/challenges/sherlock-and-the-beast 3 | public class SherlockAndTheBeast { 4 | static long[] answerArr = { -2, -1, -1, 555, -1, 33333, 555555, -1, 5 | 55533333, 555555555, 3333333333l, 55555533333l, 555555555555l, 6 | 5553333333333l, 55555555533333l, 555555555555555l }; 7 | public static void main(String[] args) { 8 | // TODO Auto-generated method stub 9 | Scanner input = new Scanner(System.in); 10 | int tests = input.nextInt(); 11 | for (int a = 0; a < tests; a++) { 12 | int n = input.nextInt(); 13 | 14 | StringBuilder output = new StringBuilder(); 15 | while (n >= 15) { 16 | n -= 3; 17 | output.append("555"); 18 | } 19 | output.append(answerArr[n]); 20 | System.out.println(output); 21 | 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /SparseArrays.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | //https://www.hackerrank.com/challenges/sparse-arrays 4 | public class SparseArrays { 5 | 6 | public static void main(String[] args) { 7 | /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ 8 | Scanner input = new Scanner(System.in); 9 | int n = input.nextInt(); 10 | HashMap map = new HashMap(); 11 | for(int a =0; a < n; a++){ 12 | String i = input.next(); 13 | if(!map.containsKey(i)){ 14 | map.put(i, 0); 15 | } 16 | map.put(i, map.get(i)+1); 17 | } 18 | int k = input.nextInt(); 19 | for(int b = 0; b < k; b++){ 20 | String query = input.next(); 21 | if(!map.containsKey(query)){ 22 | map.put(query, 0); 23 | } 24 | System.out.println(map.get(query)); 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /TheMaximumSubarray.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | import java.*; 4 | //https://www.hackerrank.com/challenges/maxsubarray 5 | public class TheMaximumSubarray { 6 | 7 | public static void main(String[] args) { 8 | /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ 9 | Scanner input = new Scanner(System.in); 10 | int k = input.nextInt(); 11 | for(int a = 0; a < k; a++){ 12 | int n = input.nextInt(); 13 | int[] arr= new int[n]; 14 | int sum = 0; 15 | int count = 0; 16 | int max = Integer.MIN_VALUE; 17 | for(int b = 0; b < n; b++){ 18 | arr[b] = input.nextInt(); 19 | if(arr[b] > max){ 20 | max = arr[b]; 21 | } 22 | if(arr[b] > 0){ 23 | sum += arr[b]; 24 | count++; 25 | } 26 | } 27 | if(count == 0){ 28 | sum = max; 29 | } 30 | int subSum = 0; 31 | int previousRecord = -1000000000; 32 | for(int b = 0; b < n; b++){ 33 | subSum += arr[b]; 34 | if(subSum > previousRecord){ 35 | previousRecord=subSum; 36 | } 37 | if(subSum < 0){ 38 | subSum = 0; 39 | } 40 | } 41 | System.out.println(previousRecord+" " + sum); 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /WeeklyChallenges_Week13_ASuperHero.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class WeeklyChallenges_Week13_ASuperHero { 4 | public static void main(String[] args) { 5 | /* 6 | * Enter your code here. Read input from STDIN. Print output to STDOUT. 7 | */ 8 | Scanner stdin = new Scanner(System.in); 9 | // Parses the number of cases 10 | int numberOfCases = Integer.parseInt(stdin.nextLine()); 11 | int numberOfLevels = 0; 12 | int enemiesPerLevel = 0; 13 | int[][] power = null; 14 | int[][] bullets = null; 15 | int[] bulletsNeededArray = null; 16 | int bulletsNecessary = 0; 17 | int bulletsNecessaryTemp = 0; 18 | int[] bestEnemyPath = null; 19 | for (int a = 0; a < numberOfCases; a++) { 20 | numberOfLevels = stdin.nextInt(); 21 | enemiesPerLevel = stdin.nextInt(); 22 | stdin.nextLine(); 23 | power = new int[numberOfLevels][enemiesPerLevel]; 24 | bullets = new int[numberOfLevels][enemiesPerLevel]; 25 | // Create 2d arrays for power and bullets and parse input data 26 | // accordingly. 27 | for (int c = 0; c < numberOfLevels; c++) { 28 | for (int b = 0; b < enemiesPerLevel; b++) { 29 | power[c][b] = stdin.nextInt(); 30 | } 31 | stdin.nextLine(); 32 | } 33 | for (int c = 0; c < numberOfLevels; c++) { 34 | for (int b = 0; b < enemiesPerLevel; b++) { 35 | bullets[c][b] = stdin.nextInt(); 36 | } 37 | if (a < numberOfCases - 1 && c < numberOfLevels-1) { 38 | stdin.nextLine(); 39 | } 40 | } 41 | bulletsNecessaryTemp = integerArrayMin(power[numberOfLevels - 1]); 42 | bulletsNecessary = 0; 43 | bulletsNeededArray = new int[enemiesPerLevel]; 44 | for (int c = 0; c < enemiesPerLevel; c++) { 45 | bulletsNeededArray[c] = bulletsNecessaryTemp; 46 | } 47 | bestEnemyPath = new int[numberOfLevels]; 48 | bestEnemyPath[numberOfLevels -1 ] = integerArrayMinIndex(power[numberOfLevels-1]); 49 | for (int c = numberOfLevels - 2; c >= 0; c--) { 50 | for (int d = 0; d < enemiesPerLevel; d++) { 51 | bulletsNeededArray[d] = bulletsNecessaryTemp + power[c][d] - (Math.min(bulletsNecessaryTemp, bullets[c][d])); 52 | } 53 | bestEnemyPath[c] = integerArrayMinIndex(bulletsNeededArray); 54 | bulletsNecessaryTemp = power[c][integerArrayMinIndex(bulletsNeededArray)]; 55 | } 56 | int sum = 0; 57 | int bulletsTemp = 0; 58 | for(int c = 0; c < numberOfLevels; c++){ 59 | System.out.print(bestEnemyPath[c]); 60 | sum += Math.max(power[c][bestEnemyPath[c]] - bulletsTemp, 0); 61 | bulletsTemp = bullets[c][bestEnemyPath[c]]; 62 | } 63 | System.out.println(); 64 | System.out.println(sum); 65 | } 66 | } 67 | 68 | public static int integerArrayMin(int input[]) { 69 | int min = Integer.MAX_VALUE; 70 | for (int a = 0; a < input.length; a++) { 71 | if (min > input[a]) 72 | min = input[a]; 73 | } 74 | return min; 75 | } 76 | public static int integerArrayMinIndex(int input[]) { 77 | int min = Integer.MAX_VALUE; 78 | int index = -1; 79 | for (int a = 0; a < input.length; a++) { 80 | if (min > input[a]){ 81 | min = input[a]; 82 | index = a; 83 | } 84 | } 85 | return index; 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /WeeklyChallenges_Week13_TaumandBday.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | import java.text.*; 4 | import java.math.*; 5 | import java.util.regex.*; 6 | /* Problem Statement 7 | Taum is planning to celebrate the birthday of his friend Diksha. There are two types of gifts that Diksha wants from Taum: one is black and the other is white. To make her happy, Taum has to buy B number of black gifts and W number of white gifts. 8 | 9 | The cost of each black gift is X units 10 | and the cost of every white gift is Y units 11 | and the cost of converting each black gift into white or white into black is Z units. 12 | Help Taum by deducing the minimum amount he needs to spend on Diksha's gifts? 13 | 14 | Input Format 15 | 16 | The first line will contain an integer T which will be the number of test cases. 17 | There will be T pair of lines. The first line of each test case will contain the value of integers B and W. Another line of each test will contain the value of integers X,Y and Z. 18 | 19 | Constraints 20 | 1<=T<=10 21 | 0<=X,Y,Z,B,W<=10^9 22 | 23 | Output Format 24 | 25 | T lines each containing output for a particular test case. 26 | */ 27 | public class WeeklyChallenges_Week13_TaumandBday { 28 | 29 | public static void main(String[] args) { 30 | /* 31 | * Enter your code here. Read input from STDIN. Print output to STDOUT. 32 | */ 33 | Scanner stdin = new Scanner(System.in); 34 | 35 | //Parses the number of cases 36 | int numberOfCases = Integer.parseInt(stdin.nextLine()); 37 | int B = 0; 38 | int W = 0; 39 | int X = 0; 40 | int Y = 0; 41 | int Z = 0; 42 | BigInteger cost = new BigInteger("0"); 43 | BigInteger bestBlackCost = new BigInteger("0"); 44 | BigInteger bestWhiteCost = new BigInteger("0"); 45 | BigInteger netBlackCost = new BigInteger("0"); 46 | BigInteger netWhiteCost = new BigInteger("0"); 47 | for(int a = 0; a < numberOfCases; a++){ 48 | 49 | //Parse the value of B and W 50 | B = stdin.nextInt(); 51 | W = stdin.nextInt(); 52 | stdin.nextLine(); 53 | 54 | //Parse the value of X, Y, and Z 55 | X = stdin.nextInt(); 56 | Y = stdin.nextInt(); 57 | Z = stdin.nextInt(); 58 | 59 | //Find the best cost for a Black or White piece, taking the minimum of the direct cost or the conversion from white to black. 60 | bestBlackCost = new BigInteger("" + Math.min(X, Y+Z)); 61 | bestWhiteCost = new BigInteger("" + Math.min(Y, X+Z)); 62 | 63 | netBlackCost = bestBlackCost.multiply(new BigInteger(B + "")); 64 | netWhiteCost = bestWhiteCost.multiply(new BigInteger(W + "")); 65 | 66 | System.out.println(netBlackCost.add(netWhiteCost)); 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /WeeklyChallenges_Week13_sherlockandanagrams.java: -------------------------------------------------------------------------------- 1 | import java.math.BigInteger; 2 | import java.util.Scanner; 3 | 4 | public class WeeklyChallenges_Week13_sherlockandanagrams { 5 | public static void main(String[] args) { 6 | /* 7 | * Enter your code here. Read input from STDIN. Print output to STDOUT. 8 | * Your class should be named Solution. 9 | */ 10 | int[] frequency = new int[26]; 11 | Scanner stdin = new Scanner(System.in); 12 | // Parses the number of cases 13 | int numberOfCases = Integer.parseInt(stdin.nextLine()); 14 | String caseString = ""; 15 | int sum = 0; 16 | for (int a = 0; a < numberOfCases; a++) { 17 | sum = 0; 18 | caseString = stdin.nextLine(); 19 | for (int start1 = 0; start1 < caseString.length(); start1++) { 20 | for (int start2 = start1; start2 < caseString.length(); start2++) { 21 | for(int length = 1; length <= caseString.length() - Math.max(start1, start2); length++){ 22 | if(start1 != start2){ 23 | String s1 = caseString.substring(start1, start1+length); 24 | String s2 = caseString.substring(start2, start2+length); 25 | //System.out.println("Start1 " + start1 + ", Start2 " + start2 + " length " + length); 26 | if (checkAnagram(s1, s2)) { 27 | sum++; 28 | //System.out.println(s1 + " " + s2); 29 | } 30 | } 31 | } 32 | } 33 | } 34 | System.out.println(sum); 35 | } 36 | } 37 | 38 | public static int count(String inputString, char testingChar) { 39 | int sum = 0; 40 | for (int a = 0; a < inputString.length(); a++) { 41 | if (inputString.charAt(a) == testingChar) { 42 | sum++; 43 | } 44 | } 45 | return sum; 46 | } 47 | public static boolean checkAnagram(String s1, String s2){ 48 | boolean anagram = true; 49 | for(int a = 0; a < 26; a++){ 50 | if (count(s1, (char) (a + 96)) != count(s2, (char) (a + 96))){ 51 | anagram = false; 52 | } 53 | } 54 | return anagram; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /binarySearch.java: -------------------------------------------------------------------------------- 1 | import java.math.BigInteger; 2 | import java.util.Arrays; 3 | import java.util.Scanner; 4 | /* 5 | * Given a sorted array (ar) and a number (V), can you print the index location of V in the array? 6 | 7 | {The next section describes the input format. You can often skip it, if you are using included methods. } 8 | 9 | Input Format 10 | There will be three lines of input: 11 | 12 | V - the value that has to be searched. 13 | n - the size of the array. 14 | ar - n numbers that make up the array. 15 | Output Format 16 | Output the index of V in the array. 17 | 18 | {The next section describes the constraints and ranges of the input. You should check this section to know the range of the input. } 19 | 20 | Constraints 21 | 1<=n<=1000 22 | -1000 <=x <= 1000 , x ∈ ar 23 | */ 24 | public class binarySearch { //Usage of the binary search function in java. 25 | public static void main(String[] args) { 26 | Scanner stdin = new Scanner(System.in); 27 | int numberToSearch = stdin.nextInt(); 28 | stdin.nextLine(); 29 | int sizeOfArray = Integer.parseInt(stdin.nextLine()); 30 | int[] input = new int[sizeOfArray]; 31 | for (int a = 0; a < sizeOfArray; a++) { 32 | input[a] = stdin.nextInt(); 33 | } 34 | 35 | System.out.println(Arrays.binarySearch(input, numberToSearch)); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /correctnessTestingInsertionSort.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class correctnessTestingInsertionSort { 5 | 6 | public static void insertionSort(int[] A) { 7 | for (int i = 1; i < A.length; i++) { 8 | int value = A[i]; 9 | int j = i - 1; 10 | while (j >= 0 && A[j] > value) { 11 | A[j + 1] = A[j]; 12 | j = j - 1; 13 | } 14 | A[j + 1] = value; 15 | } 16 | printArray(A); 17 | } 18 | 19 | static void printArray(int[] ar) { 20 | for (int n : ar) { 21 | System.out.print(n + " "); 22 | } 23 | } 24 | 25 | public static void main(String[] args) { 26 | Scanner in = new Scanner(System.in); 27 | int n = in.nextInt(); 28 | int[] ar = new int[n]; 29 | for (int i = 0; i < n; i++) { 30 | ar[i] = in.nextInt(); 31 | } 32 | 33 | insertionSort(ar); 34 | 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /flipping_bits.java: -------------------------------------------------------------------------------- 1 | import java.math.BigInteger; 2 | import java.util.Scanner; 3 | 4 | public class flipping_bits { 5 | public static void main(String[] args) { 6 | /* 7 | * Problem Statement 8 | 9 | You will be given a list of 32 bits unsigned integers. You are required to output the list of the unsigned integers you get by flipping bits in its binary representation (i.e. unset bits must be set, and set bits must be unset). 10 | 11 | Input Format 12 | 13 | The first line of the input contains the list size T. T lines follow each line having an integer from the list. 14 | 15 | Constraints 16 | 17 | 1≤T≤100 18 | 0≤integer<232 19 | Output Format 20 | 21 | Output one line per element from the list with the requested result. 22 | */ 23 | Scanner stdin = new Scanner(System.in); 24 | int numberOfCases = Integer.parseInt(stdin.nextLine()); 25 | String input; 26 | BigInteger intInput; 27 | BigInteger output; 28 | for (int a = 0; a < numberOfCases; a++) { 29 | input = stdin.nextLine(); 30 | 31 | intInput = new BigInteger(input); 32 | 33 | output = ((new BigInteger("4").multiply(new BigInteger( "" + ((int) Math.pow(2,30)))).subtract(new BigInteger("1"))).subtract(intInput)); 34 | System.out.println(output.toString()); 35 | } 36 | 37 | 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /is_fibo.java: -------------------------------------------------------------------------------- 1 | import java.math.BigInteger; 2 | import java.util.Arrays; 3 | import java.util.Scanner; 4 | 5 | public class is_fibo { 6 | public static void main(String[] args) { 7 | /* 8 | * Problem Statement 9 | 10 | You are given an integer, N. Write a program to determine if N is an element of the Fibonacci Sequence. 11 | 12 | The first few elements of fibonacci sequence are 0,1,1,2,3,5,8,13,⋯ A fibonacci sequence is one where every element is a sum of the previous two elements in the sequence. The first two elements are 0 and 1. 13 | 14 | Input Format 15 | The first line contains T, number of test cases. 16 | T lines follows. Each line contains an integer N. 17 | 18 | Output Format 19 | Display IsFibo if N is a fibonacci number and IsNotFibo if it is not a fibonacci number. The output for each test case should be displayed in a new line. 20 | 21 | Constraints 22 | 1≤T≤10^5 //Number of test cases can be anywhere up to 10,000 23 | 1≤N≤10^10 // Size of number can be anything from 1 to 10,000,000,000 (use long data structure). 24 | Sample Input 25 | 26 | 3 //number of test cases 27 | 5 28 | 7 29 | 8 30 | Sample Output 31 | 32 | IsFibo 33 | IsNotFibo 34 | IsFibo 35 | */ 36 | Scanner stdin = new Scanner(System.in); 37 | 38 | long[] fibo = new long[1000];//fibonacci has an approximate lower bound of 1.5^n, so 1000 elements should be more than enough. 39 | fibo[0] = 0; 40 | fibo[1] = 1; 41 | long x = fibo[0] + fibo[1]; 42 | 43 | int iterator = 2; 44 | while(x < 10000000000L){ //Inside this loop, we preprocess the values of fibonacci up to 10,000,000,000 45 | fibo[iterator] = fibo[iterator-1] + fibo[iterator-2]; 46 | iterator++; 47 | x = fibo[iterator-1]; 48 | //System.out.println(fibo[iterator-1]); 49 | } 50 | Arrays.sort(fibo); 51 | int numberOfCases = Integer.parseInt(stdin.nextLine()); 52 | String input; 53 | BigInteger intInput; 54 | BigInteger output; 55 | for (int a = 0; a < numberOfCases; a++) { 56 | input = stdin.nextLine(); 57 | long inputLong = Long.parseLong(input, 10); 58 | 59 | if(Arrays.binarySearch(fibo, inputLong) < 0){ 60 | // System.out.println("InputLong is fibo" + inputLong); 61 | System.out.println("IsNotFibo"); 62 | } 63 | else{ 64 | //System.out.println("InputLong is not fibo" + inputLong); 65 | System.out.println("IsFibo"); 66 | } 67 | } 68 | 69 | 70 | } 71 | } 72 | --------------------------------------------------------------------------------