2016-07-26 8 views
1

数値がNである場合、分数がP/Q(PとQはコプライム)の場合、PとQ <=Nである必要があります。 だから私はこの素朴なアプローチを思いついた。分数の数が1より小さい場合

public static void main (String[] args) throws java.lang.Exception 
    { 
    // your code goes here 
    Scanner sc = new Scanner (System.in); 
    int t = sc.nextInt();//number of test cases 
    while(t-->0){ 
     int n = sc.nextInt();//integer N 
     int count=0; 
     for(int i=1;i<=n;i++){ 
      for(int j=1;j<i;j++){ 
       if(gcd(i,j)==1) 
        count++; 
      } 
     } 
     System.out.println(count); 
    } 
    } 
    public static int gcd(int a,int b){ 
     if(b!=0) 
      return gcd(b,a%b); 
     else 
      return a; 
    } 

これはTLEとして拒否されました。それから私は値が事前に計算されていると考えました。N<=1000000です。だから私はこれを試してみました:

public static void main (String[] args) throws java.lang.Exception 
    { 
    // your code goes here 
    Scanner sc = new Scanner (System.in); 
    int[] arr = new int[1000001]; 
    arr[0]=0; 
    for(int i=1;i<1000001;i++) 
    { 
     arr[i]=arr[i-1]; 
     for(int j=i-1;j>=0;j--) 
     { 
      if(gcd(i,j)==1) 
       arr[i]++; 
     } 
    } 
    int t = sc.nextInt(); 
    while(t-->0){ 
     int n = sc.nextInt(); 
     System.out.println(arr[n]); 
    } 
    } 
    public static int gcd(int a,int b){ 
     if(b!=0) 
      return gcd(b,a%b); 
     else 
      return a; 
    } 

しかし、今では、あまりにも、N=123のためのTLEを示しています。ループが正しいように見えても何がうまくいかないのか理解できません。より良いアプローチも歓迎します。
注:TLEは制限時間を超えています

+4

TLEは何を意味するのでしょうか?あまりにも小さな努力? – subrunner

+1

Fareyシーケンスを検索したい場合があります。 https://en.wikipedia.org/wiki/Farey_sequence – dmuir

+0

@subrunner TLEは制限時間を超過 – yobro97

答えて

1

forループは正常です。 whileループで何かが間違っている、つまり条件が常にtrueに評価されていることを確認しています。それは、(t - )>の代わりに意味を持つ意味があるかもしれません。あなたが望むのは確かです。

より良いアプローチは、Farey Sequenceまたは​​のようなものを実装することです。

+0

私は長い間 'while(t - > 0) 'を使っていました。これまでにこのようなエラーが発生したことはありません。 :( – yobro97

+0

これに加えて、以前の解決策では 'N = 1'、' 2'、 '3'も' t - > 0'のTLEなしで実行しました – yobro97

+0

元のプログラムでは、ネストされたforループの時間的複雑さはO(n^2)であり、nのために1000000を入れています.2番目のプログラムではwhileループと何か関係があります。 – AlgorithmsX

0

Euler's totient functionと動的プログラミングを使用できます。

ステップ1:可能な最大値までのすべての素数を生成します。

ステップ2:すべて1 <= i <= max possible value of nについてtotient[i]を計算します。これには動的プログラミングを使用します。

  • totient[1] = 0

  • totient[i] = i - 1i

マリー(dを見つけるために、素数をループ)iを分割する任意dの主要

  • totient[i] = totient[i/d] * totient[d]ある場合p 3。既約分数の数はp/qp < q <= iであり、totient[2] + totient[3] + totient[4] + ... + totient[i]Farey sequenceの長さ)です。トータルを計算する際にも計算します。

    • numberOfFractions[1] = 0

    • numberOfFractions[i] = numberOfFractions[i-1] + totient[i]

  • 関連する問題