close
題目概要:
計算出題目規定範圍內的GCD所有總和。
解題方向:
使用輾轉相除法求出GCD,並全部加總即是答案。
程式碼:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Java | |
import java.util.Scanner; | |
class uva11417{ | |
public static void main(String args[]){ | |
Scanner sc=new Scanner(System.in); | |
int num; | |
while((num=sc.nextInt())!=0){ | |
int ans=0; | |
for(int i=1;i<num;i++){ | |
for(int j=i+1;j<=num;j++){ | |
ans+=gcd(i,j); | |
} | |
} | |
System.out.println(ans); | |
} | |
} | |
public static int gcd(int a,int b){ | |
while(a!=0 && b%a!=0){ | |
int temp=b; | |
b=a; | |
a=temp%a; | |
} | |
return a; | |
} | |
} |
文章標籤
全站熱搜