본문 바로가기
Javascript/GMA(2302~)

23.04.14 자바스크립트 최대공약수 구하기

by hyerin1201 2023. 4. 14.

HTML

<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script defer src="/script_3.js"></script>
  <link rel="stylesheet" href="/style_3.css">
  <title>Document</title>
</head>
<body>
  <div class="container">
    <h2>최대공약수 구하기</h2>
    <p>두 수를 입력한 후 [계산하기]를 클릭하세요</p>
    <form name="data">
      <input type="text" id="first" name="first">
      <input type="text" id="second" name="second">
    </form>
    <button type="button">계산하기</button>
    <div id="result"></div>
  </div>
</body>
</html>

 

CSS

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
.container {
  width: 600px;
  margin: 20px auto;
  text-align: center;
  border: 1px solid #ccc;
  padding: 10px;

  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
h2 {
  margin-bottom: 10px;
}
p {
  font-size: 14px;
  margin-bottom: 20px;
}
input {
  display: flex;
  width: 250px;
  padding: 5px 10px;
  margin-bottom: 10px;
}
button {
  width: 250px;
  padding: 5px;
  background-color: #eee;
  border: 1px solid #ccc;
  margin-bottom: 30px;
  cursor: pointer;
}
#result {
  height: 50px;
  font-size: 20px;
  text-align: center;
}

 

Javascript

const first = document.querySelector("#first");
//const first = document.querySelector("#first").value; 로 받아오면 문자열이되어버림.

const second = document.querySelector("#second");
const btn = document.querySelector("button");
const result = document.querySelector("#result");

btn.onclick = () => {
  function getGCD(n, m) {
    let max = n > m ? n : m;
    let gcd = 1;
    for(let i = 1; i <= max; i++){
      if(n % i === 0 && m % i === 0){
        gcd = i;
      }
    }
    return gcd;
  }
  result.innerText = getGCD(first.value, second.value);
}