출처: https://www.acmicpc.net/problem/12779
정보통신처에서는 2016년 6월 4일 인하 광장에서 이벤트를 진행하려고 한다. 정보통신처에서 인하 광장에 올린 게시글에 N번째로 댓글을 단 모든 학생에게 상품을 지급하기로 하였다. 단, N은 약수의 개수가 홀수여야 한다. 인하 광장을 즐겨보는 찬미는 이 이벤트에 참가하기로 하였다. 찬미는 댓글을 작성한 후 자신이 상품을 받을 확률이 얼마나 되는지 궁금해졌다. 찬미가 댓글을 작성하기 전의 총 댓글 수가 a개이고, 댓글을 작성 후의 총 댓글 수가 b개일 때 찬미의 댓글은 a보다 크고 b보다 작거나 같은 범위 안에 존재한다고 한다. 예를 들어 a가 1이고, b가 4인 경우 [2, 3, 4] 중 한 곳에 댓글이 존재한다. 이 중 약수의 개수가 홀수인 숫자는 4, 한 개이므로 상품을 받을 확률은 1/3이다. 찬미를 도와 찬미가 상품을 받을 확률을 구하는 프로그램을 작성하라.
입력
입력의 첫 줄에는 정수 a와 b가 주어진다. (1 ≤ a, b ≤ 2^60) b는 a보다 항상 크다
출력
찬미가 상품을 지급받을 확률을 기약분수 형태로 출력한다. 만약 확률이 0인 경우 0을 출력한다.
예제 입력
1 4
예제 출력
1/3
def isOddDiv(num):
if num / int(num**0.5) == int(num**0.5):
return True
return False
def gcd(n1, n2):
if n1 == 0:
return n2
return gcd(n2 % n1, n1)
a, b = map(int, input('a b: ').split())
bunmo = b - a
bunja = 0
for i in range(a+1, b+1):
if isOddDiv(i):
bunja += 1
gd = gcd(bunja, bunmo)
print(bunja//gd,'/', bunmo//gd)
2023年11月03日 21:29
package Calculator;
import java.util.Scanner;
import java.util.LinkedList;
import java.util.ListIterator;
public class CalculatorProblem {
static LinkedList<Integer> list;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
list = new LinkedList<>();
CalculatorProblem calc = new CalculatorProblem();
while(true) {
System.out.print("$ Input: ");
int before = scan.nextInt();
int after = scan.nextInt();
// Check the bound.
if(before<1 || before>after || after<1) {
System.out.println("Out of bound.");
continue;
}
// Initialization.
for(int i=before+1; i<=after; i++) {
list.add(i);
}
// Print list.
ListIterator iter = list.listIterator();
calc.printList("Before elimination", iter);
// Removes elements with an even number of divisor.
calc.removeElements(iter);
calc.printList("After elimination", iter);
// Calculate probability with winning.
System.out.printf(" -> Probability: 1/%d\n", list.size());
}
}
// Print the list.
private void printList(String contents, ListIterator iter) {
moveFirst(iter);
System.out.printf(" -> %s: ", contents);
while(iter.hasNext()) {
System.out.printf("%d ", iter.next());
}
System.out.println();
}
// Move front of first node.
private void moveFirst(ListIterator iter) {
while(iter.hasPrevious()) {
iter.previous();
}
}
// Removes elements with an even number of divisor.
private void removeElements(ListIterator iter) {
moveFirst(iter);
while(iter.hasNext()) {
int index = (int)iter.next();
if(isDivisorEven(index)%2==0) {
iter.remove();
}
}
}
// Check elements with an even number of divisor.
private int isDivisorEven(int index) {
int count = 0;
for(int i=1; i<= index; i++) {
if(index%i ==0)
count++;
}
return count;
}
}
리스트로 풀어봤습니다.
#include<stdio.h>
#include<math.h>
int main(void)
{
unsigned long long a, b;
int numer = 0, denom = 0; // numer는 분자, denom은 분모
register int i;
scanf("%lld%lld", &a, &b);
for (i = a + 1; i <= b; i++)
{
denom++;
if (round(sqrt(i)) == sqrt(i)) numer++;
}
printf("%d/%d", numer, denom);
}
c언어입니다.
2022年08月06日 02:37
import sys
def fractioneR (AA,BB) :
pass
def sonmakeR (AA,BB) :
resultt = 0
for N in range (AA+1,BB+1) :
if float(int( (N)**(1/2) )) == (N)**(1/2) : resultt += 1
return resultt
def dividermakeR (AA) :
resultlistt = []
for N in range (1,AA+1) :
if AA % N == 0 : resultlistt.append(N)
return resultlistt
def answermakeR ( AA, BB ) :
newAA = AA
newBB = BB
Alistt = dividermakeR(AA)
Blistt = dividermakeR(BB)
for Adividerr in Alistt :
if Adividerr in Blistt :
newAA = newAA // Adividerr
newBB = newBB // Adividerr
print( f'{newAA}/{newBB}' )
[a,b] = sys.stdin.readline().strip().split(' ')
a = int(a)
b = int(b)
mothernumberr = b-a
sonnumberr = sonmakeR(a,b)
answermakeR (sonnumberr , mothernumberr )
from math import gcd
a, b = map(int, input('a b : ').split(' '))
def divisor(n):
count = 0
for i in range(1,n+1):
if n % i == 0:
count += 1
if count % 2 == 1:
return True
count = 0
for i in range(a+1,b+1):
if divisor(i) == True:
count += 1
gcd = gcd(count, b-a)
print(f'{count//gcd}/{(b-a)//gcd}')
using System;
using System.Collections.Generic;
namespace FirstProgram
{
class Program
{
static int divisor(int n)
{
int get = 0;
for(int i=1; i<=n; i++)
{
if (n % i == 0)
get++;
}
return get;
}
static void Main(string[] args)
{
string[] str = Console.ReadLine().Split(' ');
List<int> arr = new List<int>();
int oddCount = 0;
for(int i=int.Parse(str[0])+1; i<=int.Parse(str[1]); i++)
{
arr.Add(i);
}
for(int i=0; i<arr.Count; i++)
{
if (divisor(arr[i]) % 2 == 1)
oddCount++;
}
Console.WriteLine(oddCount + "/" + arr.Count);
}
}
}
C#
from fractions import Fraction
while True:
a = int(input("댓글 작성 전 댓글의 수:"))
b = int(input("댓글 작성 후 댓글의 수:"))
if a >=1 and a<=2**60 and b >=1 and b<=2**60 and b>a:
break
fraction = b-a
cnt = 0
for i in range(a+1,b+1):
n =0
for k in range(1,i+1):
if i%k == 0 :
n+=1
if n%2 ==1:
cnt +=1
prob = Fraction(cnt,fraction)
print("상품을 받을 확률은 :",prob)
python 3.9입니다.
def gcd(num1, num2):
while num2 != 0:
r = num1 % num2
num1 = num2
num2 = r
return num1
a, b = [int(var) for var in input().split()]
c, d = int(b ** 0.5) - int(a ** 0.5), b - a
print(f'{c // gcd(c, d)} / {d // gcd(c, d)}' if c else 0)
결과입니다.
1 4
1 / 3
5 8
0
4 16
1 / 6
#codingdojing_2016_inha
## 최대공약수 구하기 // 유클리드 호제법
def GCD(x, y): #x > y,
if x%y == 0: return y
else: return GCD(y, x%y)
a,b = map(int,input().split())
cnt = 0
for i in range(a+1,b+1):
if (i**0.5) % 1 == 0: #i의 약수가 홀수이기 위해서는 모든 약수가 짝수개여야 함.
cnt += 1
denominator = b - a
if cnt == 0: print(cnt) #0인 경우
else:
c = GCD(denominator, cnt)
d = cnt//c
e = denominator//c
if e == 1: print(1) #1인 경우
else: print(f'{d}/{e}')
2021年08月18日 13:53
풀이 작성
코딩도장은 프로그래밍 문제풀이를 통해서 코딩 실력을 수련(Practice)하는 곳입니다.