Skip to content

Instantly share code, notes, and snippets.

@johnludwigm
Created February 13, 2018 01:34
Show Gist options
  • Save johnludwigm/ee1eac71d018af488ab3f6f51d838ba4 to your computer and use it in GitHub Desktop.
Save johnludwigm/ee1eac71d018af488ab3f6f51d838ba4 to your computer and use it in GitHub Desktop.
Solution to the Happy Numbers problem in Java.
import java.util.HashSet;
import java.util.Scanner;
import java.io.*;
public class HappyNumber {
//Note that we did not account for the fact that all permutations of a happy number's digits
//must also form happy numbers since addition commutes. This is mentioned in the README.
private final static long ten = 10;
static long squareSum(long number) {
long total = 0;
long digit;
while (number > 0) {
digit = (number % ten);
total += (digit * digit);
number /= ten;
}
return total;
}
public static boolean checkFile(String fileName) {
File file = new File(fileName);
if (file.exists()) {
return false;
}
//So the file does not already exist. Now we guarantee that the parent directory exists.
file.getParentFile().mkdirs();
return true;
}
public static void main(String[] args) {
HashSet<Long> happyNumbers = new HashSet<>();
Scanner in = new Scanner(System.in);
System.out.println("Enter how many numbers you'd like to compute: ");
int limit = in.nextInt();
in.nextLine();
System.out.println("Enter the absolute path of the output file you'd like to make: ");
String fileName = in.nextLine();
if (!checkFile(fileName)) {
System.out.println("File already exists. Now exiting program.");
System.exit(0);
}
TextOutput textOutput = new TextOutput(fileName);
happyNumbers.add((long) 1);
textOutput.writeLine(String.valueOf(1));
int count = 1;
long current = 2;
HashSet<Long> deadEnds = new HashSet<>();
while (count < limit) {
HashSet<Long> currentSet = new HashSet<>();
long number = current;
while (number != 1) {
currentSet.add(number);
number = squareSum(number);
if (deadEnds.contains(number) || currentSet.contains(number)) {
//Then the number cycles and will never ever find happiness.
deadEnds.addAll(currentSet);
break;
}
if (happyNumbers.contains(number)) {
happyNumbers.addAll(currentSet);
textOutput.writeLine(String.valueOf(current));
count++;
break;
}
}
current++;
}
textOutput.close();
in.close();
}
}
class TextOutput {
private BufferedWriter bw;
private FileWriter fw;
public TextOutput(String fileName) {
try {
this.fw = new FileWriter(fileName);
this.bw = new BufferedWriter(this.fw);
} catch (IOException e) {
e.printStackTrace();
}
}
public void writeLine(String line) {
try {
this.bw.write(line + "\n");
} catch (IOException e) {
e.printStackTrace();
}
}
public void close() {
try {
this.bw.close();
this.fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment