結果

問題 No.308 素数は通れません
ユーザー kmjpkmjp
提出日時 2015-12-01 00:46:35
言語 Python2
(2.7.18)
結果
AC  
実行時間 16 ms / 1,000 ms
コード長 951 bytes
コンパイル時間 829 ms
コンパイル使用メモリ 6,912 KB
実行使用メモリ 7,168 KB
最終ジャッジ日時 2024-11-27 18:05:03
合計ジャッジ時間 4,308 ms
ジャッジサーバーID
(参考情報)
judge4 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 107
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
import math
import random

N=input()

isok=[0]*105
vis=[0]*105
for i in range(2,105):
	for j in range(2,i):
		if i%j==0:
			isok[i]=1

def ok(N,M):
	q=[1]
	while len(q) > 0:
		v = q[-1]
		q.pop()
		
		for t in (v-1,v+1,v-M,v+M):
			if v%M==1 and t==v-1:
				continue
			if v%M==0 and t==v+1:
				continue
			if t<=0 or t>N:
				continue
			if isok[t] and vis[t]<M:
				vis[t]=M
				q.append(t)
	
	if vis[N]==M:
		return 1
	return 0

def isprime(v):
	d = v-1
	s = 0
	while d%2==0:
		s += 1
		d /= 2
	
	for i in range(100):
		a = random.randrange(0,v-2)+1
		r = pow(a,d,v)
		if r==1 or r==v-1:
			continue
		ng = 0
		for j in range(s):
			r = pow(r,2,v)
			if r == v-1:
				ng = 1
		if ng==0:
			return 0
	
	return 1


if N>=100:
	random.seed()
	for v in range(8,100,2):
		if isok[v+1]==0:
			continue
		if N%v!=1:
			print v
			break
		if isprime(N-v)==0:
			print v
			break
else:
	for M in range(2,105):
		if ok(N,M):
			print M
			break

0