2012-08-12 5 views
1

모의 검사 용지에서이 질문에 답해야합니다. 'from'숫자를 'n'숫자에 곱해야합니다. 즉, * from (from + 1) (from + 2) ... * n.Java - while 루프를 사용하여 계산 문제 해결

while 루프를 사용하여이 문제를 해결해야합니다. 나는 지금까지 이것을했으며 무엇을해야할지 확신하지 못했습니다.

class Fact { 

    private int factPartND(final int from, final int n) { 

     int c = 1; 
     int z = from; 
     int y = n; 
     int num = 0; 

     while (y >= z) { 

      num += from * (from + c);// need to stop multiplying from for each 
            // iteration? 
      c++; 
      y--; 
     } 

     return num; 
    } 

    public static void main(String[] args) { 
     Fact f = new Fact(); 
     int test = f.factPartND(5, 11); 
     System.out.println(test); 
    } 

} 
+0

출력이 이상적으로 5 * 6 * 7 * ... * 11이어야합니까? –

+0

네 목표는 – nsc010

답변

3

귀하의 계산은 다음과 같습니다 루프의 한 반복 각 요인

from * (from + 1) * (from + 2) * ... * (from + n) 

생각합니다. 당신이 (from + n)하여 누적 값을 곱까지

그래서 두 번째 반복 등 (from + i), 어디 from < i < n에 의해 (from + 1)하여 누적 값, 나중에 다른 반복을 곱하여, 그리고해야한다.

코드가 매우 유사합니다. 모든 반복에서 (from + c)이 있지만 연산이 잘못되었습니다.

그리고 언급 된 바와 같이 그냥 테스트 c에 충분 때, 그것은 혼란을 조금 루프 추적 할 cy을 사용합니다.

-2
public class Fact { 

    private int factPartND(final int from, final int n) { 
     int m = 1; 
     int result = from; 

     while (m <= n) { 
      result *= (from + m++); 
     } 

     return result; 
    } 

    public static void main(String[] args) { 
     Fact f = new Fact(); 
     int test = f.factPartND(5, 8); 
     System.out.println(test); 
    } 
} 

5, 11로하면 오버 플로우가 발생합니다. int 대신 BigInteger를 사용해야합니다. 이 같은

+0

숙제가 아니라 예전에 숙제가 아닌데도 '숙제'라는 태그를달라고 요청한 적이있다. – nsc010

-3

아마 뭔가 :

package homework; 
public class Homework { 

    public static int fact(int from, int to){ 
    int result = 1; 
    while(to>0){ 
     result*=from+to; 
     to--; 
    } 
    return result*from; 
    } 
    public static void main(String[] args) { 
    System.out.println(fact(2,4)); 
    } 
} 
+0

숙제가 아니라면 이전에 mod에 ' 숙제 '표는 과거 논문의 개정판 임에도 불구하고 – nsc010

4

당신의 while 루프 조건에 문제가 있습니다.

while(y>=z) 
{ 
    .... 
} 

은 n + 1 번 코드를 실행합니다. 즉, 5에서 11까지 실행하려면이 조건을 12까지 실행할 수 있습니다.

while 루프에서 while(y>z) 조건을 사용하는 것이 더 좋습니다.

관련 문제