Skip to content

Instantly share code, notes, and snippets.

@bijay-shrestha
Last active May 16, 2021 16:13
Show Gist options
  • Save bijay-shrestha/dc57cbb36e491e96a7106f832858579c to your computer and use it in GitHub Desktop.
Save bijay-shrestha/dc57cbb36e491e96a7106f832858579c to your computer and use it in GitHub Desktop.
Question: Finding the Next Perfect Square with Vanilla Java
package com.maharshi.practice;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import java.util.Scanner;
@SpringBootApplication
@Slf4j
/**
* E.g: The Next perfect square of
* 6 --> 9,
* 36 --> 49
* 0 should be 1 and,
* all negative integer number such as '-5' should be 0.
*/
public class PracticeApplication {
public static void main(String[] args) {
SpringApplication.run(PracticeApplication.class, args);
}
@Bean
public ApplicationRunner init() {
return args -> {
log.info("##################¡¡¡ INITIALIZING INIT ¡¡¡##################");
Scanner scanner = new Scanner(System.in);
System.out.print("FIND THE NEXT SQUARE OF: ");
int number = scanner.nextInt();
log.info("THE NEXT PERFECT SQUARE OF {} IS --> {} ", number, findNextPerfectSquareOf(number));
};
}
private boolean isPerfectSquare(int number) {
if (number != 0) {
if (number > 0) {
for (int i = 0; i < number; i++) {
if (number == i * i) {
return true;
}
}
return false;
} else {
log.info("##################¡¡¡ PROCESSING NEGATIVE VALUE ¡¡¡##################");
int newInt = Math.abs(number);
for (int i = 0; i < newInt; i++) {
if (newInt == i * i) {
return true;
}
}
}
} else {
return true;
}
return false;
}
private int findNextPerfectSquareOf(int number) {
int lastIteratedValue = 0;
boolean perfectSquare = false;
if (number != 0) {
if (number > 0) {
for (int i = 1; i <= number; i++) {
lastIteratedValue = i;
if (number == i * i) {
perfectSquare = true;
log.info("##################¡¡¡ PERFECT SQUARE MATCHED ¡¡¡##################");
break;
}
}
log.info("Last iterated value :: {}", lastIteratedValue);
if (perfectSquare) {
return (lastIteratedValue + 1) * (lastIteratedValue + 1);
} else {
log.info("##################¡¡¡ {}, IS NOT A PERFECT SQUARE, BUTTTTTTT ¡¡¡##################", lastIteratedValue);
for (int i = lastIteratedValue; i <= number; i++) {
if (isPerfectSquare(i)) {
return i;
}
number++;
}
}
} else {
return 0;
}
} else {
return 1;
}
return 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment