[Programmers] 정수 제곱근 판별 - 연습문제

동민·2021년 3월 10일
// 정수 제곱근 판별 - 연습문제
public class SqrtN {
	public long solution(long n) {
		double sqrtN = Math.sqrt(n); // 반복되는 Math.sqrt(n) 코드를 sqrtN 변수에 저장해 놓음으로써 불필요한 반복계산을 줄인다. 코드를 간결하게 작성하는것 보다 반복계산을 줄여 속도를 높이는것이 중요하다.
		return (long) ((sqrtN - Math.floor(sqrtN) == 0) ? Math.pow(sqrtN + 1, 2) : -1);
		
		// return (long) ((Math.sqrt(n) - Math.floor(Math.sqrt(n)) == 0) ? Math.pow(Math.sqrt(n) + 1, 2) : -1); // Math.sqrt(n) 불필요한 반복계산이 잦음
	}

	public static void main(String[] args) {
		SqrtN s = new SqrtN();

		System.out.println(s.solution(121));
		System.out.println(s.solution(3));

	}

}
  • 반복되는 Math.sqrt(n) 코드를 sqrtN 변수에 저장해 놓음으로써 불필요한 반복계산을 줄인다.
    코드를 간결하게 작성하는것 보다 반복계산을 줄여 속도를 높이는것이 중요하다.
profile
BE Developer

0개의 댓글