2017-11-30 10 views
0

실시간으로 4 분의 1 초도 걸리지 않지만이 프로세스가 완료되는 데 최대 5 초가 걸린다고 제 코드가보고하는 이유는 무엇입니까?스톱워치가 정확한 시간을보고하지 않습니다.

스톱워치와 관련된 코드를 굵게 표시하려고합니다. 스톱워치 관련 내용을 모두 살펴 보지 않아도됩니다. 친절하니 이것이 내 첫 게시물이기 때문에 어색해하면 미안 해요. 코드가 굵게 표시되지 않으면 문제의 조각 주위에 **가 표시됩니다.

* 배경 : 수학 에세이 용입니다. 프라임 팩터를 찾아내는 데 걸리는 시간을 알려주는 프로그램입니다. 그것은 주요 요인을 찾는 데 노력하고 있지만 스톱워치는 몇 초 안에 말도 안되는 숫자를보고합니다. 또한,이 코드가 가장 많이 스톱워치, 사용자 입력 기능, 반복과

http://www.geeksforgeeks.org/print-all-prime-factors-of-a-given-number/

에 의해 영향을 받는다 내 자신의 생각이나 다른 사람의 도움 *

// Program to print all prime factors 
import java.io.*; 
import java.lang.Math; 
import java.util.Scanner; 
import java.text.DecimalFormat; 

class primeFactorer4 
{ 
    **static long startTime = System.nanoTime();** 
    // A function to print all prime factors 
    // of a given number n 
    public static void primeFactors(long n) 
    { 
     // Print the number of 2s that divide n 
     while (n%2==0) 
     { 
      System.out.print(2 + " "); 
      n /= 2; 
     } 

     // n must be odd at this point. So we can 
     // skip one element (Note i = i +2) 
     for (int i = 3; i <= Math.sqrt(n); i+= 2) 
     { 
      // While i divides n, print i and divide n 
      while (n%i == 0) 
      { 
       System.out.print(i + " "); 
       n /= i; 
      } 
     } 

     // This condition is to handle the case whien 
     // n is a prime number greater than 2 
     if (n > 2) 
      System.out.print(n); 
    } 

    public static void main (String[] args) 
    { 
     Console console = System.console(); 
     String input = console.readLine("Enter input:"); 
     long n = Long.valueOf(input); 
     for (int k=1; k<=10; k++) 
    { 
     primeFactors(n); 
     System.out.println(" Try " + k); 
    } 
     **double endTime = System.nanoTime(); 
     double totalTime = endTime - startTime; 
     DecimalFormat totalTimeFormat = new DecimalFormat("##.###"); 
     System.out.println(" Time taken in seconds:" + totalTimeFormat.format(totalTime/10/1000000000));** 
     primeFactorer4.main(args); 
    //reason for the weird division is for clarity. "totalTime" is the time surpassed 
    //to repeat all the methods, the "10" in the middle is to get the mean total time 
    //of all the primeFactors cycles, and the "1000000000" at the end is to convert nanoseconds into seconds 
    } 
} 

이유와 하나 추가되고 primeFactors에 10 번 전화를 한 이유는 내 컴퓨터가 내게 의미있는 결과를주기를 원했기 때문입니다. 실험을 할 때 IV 수준을 3 번 (또는 그 이상) 반복하여 정확한 결과를 얻으 려한다면 결과

+0

'for' 루프에서이 방법을 사용하고 코드를보다 깨끗하게 만들 수 있습니다. – UghThatGuyAgain

+0

컴퓨터 수학은 과학적 실험이 아닙니다. 열 번 호출하면 무의미합니다. –

+0

이것은 전체 실험이 아닙니다. 나는이 결과를 숫자와 시간의 크기와 주요 요인을 찾는 시간과 연관 시켜서 회귀선을 찾았습니다. 선생님이 저에게 말한 것은 수학과 관련된 LOL을 만드는 데 필요한 최소값입니다. 필자의 주제는 주요한 요소이며, 암호를 논의 할 때 에세이로서 흥미로운 일차적 요소를 만들기 위해 내가 아는 유일한 방법이다. – regazzo

답변

0

나는 당신을 위해 무언가를 썼다. 나는 이것이 더 빠르고 더 정확할 수 있다고 생각하지만 어떤 진술을 실행하는 데는 시간이 걸리므로 정확히 정확할 수는 없다는 것을 명심하라.

long start= System.currentTimeMillis(); //start time 
//Insert code here 
long difference = System.currentTimeMillis(); //finish time 
difference -= start; 
System.out.println("Time took to run code was " + difference);; //Print the amount of time that it took 
+0

고마워 brenann, 너는 복잡하지 않고 내 것보다 훨씬 깔끔하게 보이지만 내 솔루션을 발견하고 잘 작동하고있다. – regazzo

1

알았어. 내 문제를 해결 했어. println 명령을 startTime 및 endTime 변수에 넣었습니다. startTime 변수가 시작되었을 때 프로그램이 시작되었을 때 시작되었음을 알았습니다. 사용자가 인수 할 숫자를 입력 할 때가 아닙니다. 이제는 내 개인적인 입력 속도와 관련이 없다고 느끼는 적절한 결과를 얻고 있습니다.

프로그램에 관심이있는 사용자는이 문제의 해결 방법을 적용하거나 단순히 솔루션과 문제의 대비를 확인하는 데 관심이 있습니다. 새 코드는 다음과 같습니다.

// Program to print all prime factors 
import java.io.*; 
import java.lang.Math; 
import java.util.Scanner; 
import java.text.DecimalFormat; 

class primeFactorer4 
{ 

    // A function to print all prime factors 
    // of a given number n 
    public static void primeFactors(long n) 
     { 
      // Print the number of 2s that divide n 
      while (n%2==0) 
      { 
       System.out.print(2 + " "); 
       n /= 2; 
      } 

      // n must be odd at this point. So we can 
      // skip one element (Note i = i +2) 
      for (int i = 3; i <= Math.sqrt(n); i+= 2) 
      { 
       // While i divides n, print i and divide n 
       while (n%i == 0) 
       { 
        System.out.print(i + " "); 
        n /= i; 
       } 
      } 

      // This condition is to handle the case whien 
      // n is a prime number greater than 2 
      if (n > 2) 
       System.out.print(n); 
     } 



    public static void main (String[] args) 
    { 
     Console console = System.console(); 
     String input = console.readLine("Enter input:"); 
     long n = Long.valueOf(input); 
     long startTime = System.nanoTime(); 
     System.out.println(startTime); 
     for (int k=1; k<=10; k++) 
     { 
      primeFactors(n); 
      System.out.println(" Try " + k); 
     } 
     double endTime = System.nanoTime(); 
      System.out.println(endTime); 
      double totalTime = endTime - startTime; 
      DecimalFormat totalTimeFormat = new DecimalFormat("##.##########"); 
      System.out.println(" Time taken in seconds:" + totalTimeFormat.format(totalTime/10/1000000000)); 
     primeFactorer4.main(args); 
    //reason for the weird division is for clarity. "totalTime" is the time surpassed 
    //to repeat all the methods, the "10" in the middle is to get the mean total time 
    //of all the primeFactors cycles, and the "1e9" at the end is to convert nanoseconds into seconds 
    } 
}