11 พฤศจิกายน 2556

Problem 4/11/56

Problem


Problem I 
• Write a Java method, isMultiple, that takes two long values, n and m, and returns true if and only if n is a multiple of m, that is, n = m∙i for some integer i.
– จงสร้างเมธอดในภาษา Java ชื่อ isMultiple ที่รับพารามิเตอร์สองตัวแบบ long คือ n และ m ตามลำดับ (เป็นบวก ลบ หรือศูนย์ ก็ได้) แล้วให้ค่ากลับคืนเป็นจริง ก็ต่อเมื่อ n มีค่าเป็นจำนวนเท่าของ m หรือกล่าวได้ว่า มีเลขจำนวนเต็ม i ที่คูณกับ m แล้ว ได้ค่าเท่ากับ n



Problem II 

• Write a Java method, isOdd, that takes an int n and returns true if and only if n is odd. Your method cannot use the multiplication, modulus, or division operators, however.
– จงสร้างเมธอดในภาษา Java ชื่อ isOdd ที่รับพารามิเตอร์หนึ่งตัวแบบ int ชื่อ n และให้ค่ากลับคืนเป็นจริง ก็ต่อเมื่อ n เป็นเลขคี่ (ห้ามใช้การคูณ*, การหารเหลือเศษ %, และการหาร /)



Problem III 

• Write a Java method, sum, that takes a positive integer n and returns the sum of all the positive integers smaller than n.
– จงสร้างเมธอดในภาษา Java (ใชชื้่อ sum) ที่มีพารามิเตอร์แบบ int ที่ เป็นบวก ชื่อ n และให้ค่ากลับคืน เป็นผลรวมของเลขจำนวนเต็มบวกทุกตัวที่น้อยกว่า n



Problem IV 
• Write a Java method that takes an array of int values and determines if there is a pair of numbers in the array whose product is odd.
– จงสร้างเมธอดในภาษา Java (ใชชื้่ออะไรก็ได้) ที่มีพารามิเตอร์เป็นอาร์เรย์แบบ int และให้ค่ากลับคืนเป็นจริงก็ต่อเมื่อ มีเลขจำนวนสองตัวในอาร์เรย์ที่ผลคูณเป็นเลขคี่ 
int i = 0;
int j = i+1;
int[] n = {  1, 2, 3, 4};

void setup() {
  println(isArrayOdd(n));
}

boolean isArrayOdd(int[] n) {
  if ((n[i]*n[j])%2==1) {
    return true;
  }
  if (i<n.length-1) {
    if (j<n.length) {
      j++;
    }
    else if (j==n.length) {
      i++;
      j = i+1;
    }
  }
  return isArrayOdd(n);
}

ไม่มีความคิดเห็น:

แสดงความคิดเห็น