DESENV. E IMPLEMENTAÇÃO DE ALGORITMOS 29/09/2018. Este caderno contém 11 páginas com a descrição de 10 problemas definidos a seguir:

Documentos relacionados
DESENV. E IMPLEMENTAÇÃO DE ALGORITMOS 17/09/2016. Este caderno contém 11 páginas com a descrição de 10 problemas definidos a seguir:

DESENV. E IMPLEMENTAÇÃO DE ALGORITMOS 10/09/2016. Este caderno contém 11 páginas com a descrição de 10 problemas definidos a seguir:

Como escrever para o Enem: roteiro para uma redação nota (Portuguese Edition)

DESENV. E IMPLEMENTAÇÃO DE ALGORITMOS 16/09/2017. Este caderno contém 11 páginas com a descrição de 10 problemas definidos a seguir:

Como testar componentes eletrônicos - volume 1 (Portuguese Edition)

Bíblia do Obreiro - Almeida Revista e Atualizada: Concordância Dicionário Auxílios Cerimônias (Portuguese Edition)

Comportamento Organizacional: O Comportamento Humano no Trabalho (Portuguese Edition)

Vaporpunk - A fazenda-relógio (Portuguese Edition)

Laboratório de Algoritmos Avançados Capítulo 7

Algoritmos Avançados Capítulo 8

Guia para Formacao de Analistas de Processos: Gestão Por Processos de Forma Simples (Portuguese Edition)

O candomblé e seus orixás (Coleção Autoconhecimento) (Portuguese Edition)

Homework Set #4 Solutions

Poder sem limites - o caminho do sucesso pessoal pela programação neurolinguística

As 100 melhores piadas de todos os tempos (Portuguese Edition)

Pesquisa Qualitativa do Início ao Fim (Métodos de Pesquisa) (Portuguese Edition)

Um olhar que cura: Terapia das doenças espirituais (Portuguese Edition)

GUIÃO F. Grupo: Minho. 1º Momento. Intervenientes e Tempos. Descrição das actividades

Biscuit - potes (Coleção Artesanato) (Portuguese Edition)

Dermatologia Clínica. Guia Colorido Para Diagnostico e Tratamento (Em Portuguese do Brasil)

GERENCIAMENTO PELAS DIRETRIZES (PORTUGUESE EDITION) BY VICENTE FALCONI

GUIÃO I. Grupo: Continente e Ilha. 1º Momento. Intervenientes e Tempos. Descrição das actividades

Vendors Enquiries for RFP 003/2015

A dança do corpo vestido: Um estudo do desenvolvimento do figurino de balé clássico até o século XIX (Portuguese Edition)

Direito Processual Civil (Coleção Sucesso Concursos Públicos e OAB) (Portuguese Edition)

A Vivência do Evangelho Segundo o Espiritismo (Portuguese Edition)

ATLAS COLORIDO DE ANATOMIA VETERINáRIA DE EQUINOS (EM PORTUGUESE DO BRASIL) BY STANLEY H. ASHDOWN RAYMOND R. DONE

UNIT 5: Review (UNIDADE 5: Revisão)

Empreendedorismo: Dando Asas ao Espírito Empreendedor (Portuguese Edition)

DIAGNÓSTICO DE MATEMÁTICA

ZECA - DEIXA O SAMBA ME LEVAR (Portuguese Edition)

Princípios de Direito Previdenciário (Portuguese Edition)

TDD Desenvolvimento Guiado por Testes (Portuguese Edition)

Farmacologia na Pratica de Enfermagem (Em Portuguese do Brasil)

Atividade Física Adaptada: Qualidade de Vida para Pessoas com Necessidades Especiais (Portuguese Edition)

Modelagem de Processos com BPMN (2ª edição) (Portuguese Edition)

O PRíNCIPE FELIZ E OUTRAS HISTóRIAS (EDIçãO BILíNGUE) (PORTUGUESE EDITION) BY OSCAR WILDE

Introdução A Delphi Com Banco De Dados Firebird (Portuguese Edition)

Receitas na Pressão - Vol. 01: 50 Receitas para Panela de Pressão Elétrica (Portuguese Edition)

Aposentadoria e INSS: Entenda como funcionam e defenda-se (Coleção Seus Direitos) (Portuguese Edition)

Administração de Recursos Humanos: Fundamentos Básicos (Série Recursos Humanos) (Portuguese Edition)

Endomarketing de A a Z (Portuguese Edition) By Analisa de Medeiros Brum

Conceitos de Linguagens de Programação (Portuguese Edition)

Alfabetizar letrando na biblioteca escolar (Coleção biblioteca básica de alfabetização e letramento) (Portuguese Edition)

Curso Completo de Memorização (Portuguese Edition)

Meu Filho é Alérgico! E Agora? (Portuguese Edition)

Energia dos Chakras, Saúde e Autotransformação (Portuguese Edition)

TEN CATE. HISTOLOGIA ORAL (EM PORTUGUESE DO BRASIL) BY ANTONIO NANCI

Da Emoção à Lesão: um Guia de Medicina Psicossomática (Portuguese Edition)

COMPUTAÇÃO E PROGRAMAÇÃO

Dinâmicas de leitura para sala de aula (Portuguese Edition)

Abraçado pelo Espírito (Portuguese Edition)

GERENCIAMENTO DA ROTINA DO TRABALHO DO DIA-A-DIA (EM PORTUGUESE DO BRASIL) BY VICENTE FALCONI

Cartomancia: Conhecimento através das cartas (Coleção Autoconhecimento) (Portuguese Edition)

O Jardim Secreto - Coleção Reencontro Infantil (Em Portuguese do Brasil)

O princípio 80/20: Os segredos para conseguir mais com menos nos negócios e na vida (Portuguese Edition)

Labrador: Guia prático ilustrado (Coleção Pet Criador) (Portuguese Edition)

TDD Desenvolvimento Guiado por Testes (Portuguese Edition) Kent Beck

Impostos Federais Estaduais e Municipais (Portuguese Edition)

Atlas de Acupuntura Veterinária. Cães e Gatos (Em Portuguese do Brasil)

Adoção: guia prático doutrinário e processual com as alterações da Lei n , de 3/8/2009 (Portuguese Edition)

PL/SQL: Domine a linguagem do banco de dados Oracle (Portuguese Edition)

Introdução A Delphi Com Banco De Dados Firebird (Portuguese Edition)

Pesquisa de Marketing: Uma Orientação Aplicada (Portuguese Edition)

Ligações Entre NANDA, NOC e NIC. Diagnósticos, Resultados e Intervenções (Em Portuguese do Brasil)

Astrologia, Psicologia e os Quatro Elementos (Portuguese Edition)

PL/SQL: Domine a linguagem do banco de dados Oracle (Portuguese Edition)

Conversação Para Viagem - Inglês (Michaelis Tour) (Portuguese Edition)

2ª AVALIAÇÃO/ º ANO / PRÉ-VESTIBULAR PROVA 1-25/04/2015 PROVA DISCURSIVA

Aprendi A Fazer Sexo Na Bíblia (Portuguese Edition)

Guião N. Descrição das actividades

Espionagem e Vigilância Eletrônica (Portuguese Edition)

Pesquisa Qualitativa do Início ao Fim (Métodos de Pesquisa) (Portuguese Edition)

Introdução A Delphi Com Banco De Dados Firebird (Portuguese Edition)

Higiene e Vigilância Sanitária de Alimentos (Portuguese Edition)

Fr A Lógica Da Resolução Das Questões Usando Apenas Multiplicação E Divisão (Portuguese Edition)

Ganhar Dinheiro Em Network Marketing (Portuguese Edition)

Rádio Escolar: uma experiência de letramento midiático (Coleção Trabalhando com... na escola Livro 4) (Portuguese Edition)

Direito & Rock o Brock e as Expectativas da Constituição 1988 e do Junho de 2013 (Portuguese Edition)

30 Páginas para mudar a sua vida (Portuguese Edition)

Administração de Recursos Humanos: Fundamentos Básicos (Série Recursos Humanos) (Portuguese Edition)

Como deixar seus cabelos lindos e saudáveis (Coleção Beleza) (Portuguese Edition)

Os conflitos entre palestinos e israelenses: A trajetória dos fatos históricos e o direito internacional (Portuguese Edition)

Direito Processual Civil (Coleção Sucesso Concursos Públicos e OAB) (Portuguese Edition)

O guia do enxoval do bebê nos Estados Unidos: Dicas e segredos da maior especialista de compras em Miami, Orlando e Nova York (Portuguese Edition)

Biscuit - potes (Coleção Artesanato) (Portuguese Edition)

Meditacao da Luz: O Caminho da Simplicidade

América Andina: integração regional, segurança e outros olhares (Portuguese Edition)

Uma introdução à indecilibidade a forma máxima de complexidade!

Reabilitação Neurológica (Em Portuguese do Brasil)

Ética na Propaganda (Portuguese Edition)

Certificação PMP: Alinhado com o PMBOK Guide 5ª edição (Portuguese Edition)

Medicina e Meditação - Um Médico Ensina a Meditar (Portuguese Edition)

Sermões expositivos em todos os livros da Bíblia - Novo Testamento: Esboços completos que percorrem todo o Novo Testamento (Portuguese Edition)

Esboços e Sermões Completos para Ocasiões e Datas Especiais: Mensagens Bíblicas para Todas as Datas da Vida Cristã (Portuguese Edition)

EGAN. FUNDAMENTOS DA TERAPIA RESPIRATÓRIA (EM PORTUGUESE DO BRASIL) BY CRAIG L. SCANLAN

Talento para a vida: descubra e desenvolva seus pontos fortes (Portuguese Edition)

Transcrição:

DESENV. E IMPLEMENTAÇÃO DE ALGORITMOS 29/09/2018 Este caderno contém 11 páginas com a descrição de 10 problemas definidos a seguir: A Big Mod (Big Mod - Valladolid 374) B - Carmichael Numbers (Valladolid 10006) C - Ignoring Digits (Valladolid 10993) D Halloween Treats (Valladolid 11237) E - Números pseudoprimos (Pseudoprime numbers - Valladolid 11287) F - Múltiplos tipo binário*3 (Binary*3 Type Multiple - Valladolid 11392) G - Multiple of 17 (Valladolid 11879) H - Cryptography Reloaded (Valladolid 1431) I - Problema de Euclides (Valladolid 10104) J - RSA (Valladolid 12799) Boa sorte. 1

Calcule Problema A (Valladolid 374) Big Mod para valores grandes de B, P, e M usando um algoritmo eficiente. (Ok, este problema tem uma dependência de tempo!!!.) Entrada Três valores inteiros (em ordem B, P, M ) serão lidos, um por linha. B e P são inteiros na faixa 0 a 2147483647, inclusive. M é um inteiro na faixa 1 a 46340, inclusive. Saída O resultado da expressão. Um único inteiro. Exemplo de entrada 3 18132 17 17 1765 3 2374859 3029382 36123 Exemplo de Saída 13 2 13195 2

Problema B (Valladolid 10006) Carmichael Numbers Um tópico importante hoje em dia na Computação é a Criptografia. Algumas pessoas até mesmo pensam que Criptografia é o único campo importante na Ciência da Computação e que a vida não vale a pena sem Criptografia. Alvaro é uma dessas pessoas, e está projetando um conjunto de procedimentos da criptografia para cozinhar uma paella. Alguns algoritmos da criptografia que ele implementa usam primos grandes. Mas checar se um número é primo ou não, não é fácil. A Força Bruta pode requerer a divisão do número pelos primos menores que sua raiz quadrada. Para números grandes, o tempo e a memória requeridas são certamente ruins para sua paella. Entretanto, existem alguns testes probabilísticos que oferecem alta confiabilidade a custo baixo. Um deles é o teste de Fermat. Seja a um número aleatório entre 2 e n - 1 (n é o número cuja primalidade está em teste) Então, n é provavelmente primo se a seguinte equação for satisfeita: Se um número passa no teste de Fermat várias vezes, então tem alta probabilidade de ser primo. Infelizmente, há más notícias. Alguns números que não são primos passam no teste de Fermat para todos os números inferiores a ele. Esses números são chamados de números de Carmichael. Neste problema, pede-se que você escreva um programa para testar se um dado número é um número de Carmichael. Aquele time que fizer a tarefa vai provar a deliciosa paella. Entrada Consistirá de uma série de linhas, cada uma contendo um número pequeno n ( 2 < n < 65000). Um número n = 0 finaliza a entrada e não deve ser processado. Saída Para cada número da entrada, você deve imprimir se ele é de Carmichael ou não, como mostrado no exemplo. Exemplo de Entrada 1729 17 561 1109 431 0 Exemplo de Saída The number 1729 is a Carmichael number. 17 is normal. The number 561 is a Carmichael number. 1109 is normal. 431 is normal. 3

Problema C (Valladolid 10993) Ignoring Digits When representing a number in decimal format, we need the ten digits '0' to '9'. If we are only allowed to use a subset of the ten decimal digits, there is only a limited number of numbers we can represent. If, for example, we only can use the digits '1' and '2', the numbers 11 and 12 can be represented, but the number 13 can not. If we scan the multiples of 13: 13, 26, 39, 52, 65, 78, 91, 104, 117, 130, 143, 156, 169, 182, 195, 208, 221, etc., we see that 221 is the smallest multiple of 13 that can be represented using only the digits '1' and '2'. In this problem you are asked to give the smallest multiple of a certain number that can be represented using a given subset of the decimal digits. This multiple can be the number itself, but it has to be greater than zero. Input The input consists of several cases, each on a line by itself. Each line has two numbers F and N. F is a number composed of the digits you are allowed to use in the representation. It has a minimum of 1 and a maximum of 10 unique digits in descending order. N is the number for which you are to find the multiple. It is greater than zero, but smaller than 100000. A line with two zeros ends the input and should not be processed. Output For every case in the input, one line containing the smallest multiple of N that can be represented using the digits in F. If such a multiple of N doesn't exist, print the word "impossible" (without the quotes). Never print leading zeros. Sample Input 1 11 21 12 21 13 9876543210 12345 43210 56789 97531 2 0 0 Output for Sample Input 11 12 221 12345 1022202 impossible 4

Problema D (Valladolid 11237) Halloween treats Every year there is the same problem at Halloween: Each neighbour is only willing to give a certain total number of sweets on that day, no matter how many children call on him, so it may happen that a child will get nothing if it is too late. To avoid conflicts, the children have decided they will put all sweets together and then divide them evenly among themselves. From last year's experience of Halloween they know how many sweets they get from each neighbour. Since they care more about justice than about the number of sweets they get, they want to select a subset of the neighbours to visit, so that in sharing every child receives the same number of sweets. They will not be satisfied if they have any sweets left which cannot be divided. Your job is to help the children and present a solution. Input Specification The input contains several test cases. The first line of each test case contains two integers c and n ( 1 c n 100000 ), the number of children and the number of neighbours, respectively. The next line contains n space separated integers a 1,..., a n ( 1 a i 100000 ), where a i represents the number of sweets the children get if they visit neighbour i. The last test case is followed by two zeros. Output Specification For each test case output one line with the indices of the neighbours the children should select (here, index i corresponds to neighbour i who gives a total number of a i sweets). If there is no solution where each child gets at least one sweet, print "no sweets" instead. Note that if there are several solutions where each child gets at least one sweet, you may print any of them. Sample Input 4 5 1 2 3 7 5 3 6 7 11 2 5 13 17 0 0 Sample Output 3 5 2 3 4 5

Problema E (Valladolid 11287) Números pseudoprimos O Pequeno Teorema de Fermat afirma que, para qualquer número primo p e para qualquer inteiro a > 1, temos a p a (mod p). Ou seja, se elevamos a à p -ésima potência e dividimos por p, o resto é a. Alguns (mas não muitos) valores não primos p, conhecidos como pseudoprimos base-a, têm essa propriedade para alguns a. (E alguns, conhecidos como Números de Carmichael, são pseudoprimos base-a para todo valor a.) Dados 2 < p 1,000,000,000 e 1 < a < p, determine se p é ou não um pseudoprimo base-a. A entrada contém vários casos de teste seguidos por uma linha contendo "0 0". Cada caso de teste consiste de uma linha contendo p e a. Para cada teste, imprima "yes" se p é um pseudoprimo base-a; de outra forma imprima "no". Exemplo de entrada 3 2 10 3 341 2 341 3 1105 2 1105 3 0 0 Exemplo de saída no no yes no yes yes 6

Problema F (Valladolid 11392) Múltiplos tipo binário*3 Mahbub acha que ele descobriu algo interessante mas ele não tem certeza se ele está certo ou não. Para cada inteiro ele consegue achar um múltiplo composto apenas por 3s e 0s. Você pode ajudá-lo? Você receberá um inteiro positivo K. Você tem que encontrar um múltiplo positivo de K que é composto apenas por 3s e 0s. Além disso, os dígitos deste múltiplo deve estar em ordem não-crescente. Se houver mais de um múltiplo você deve escolher o que menor em tamanho. Se ainda assim houver mais de um múltiplo remanescente, então escolha o lexicograficamente maior. Por exemplo, Para K=4, nosso múltiplo desejado é 300. Para K=7, é 333333. Para K=14, é 3333330. Entrada A entrada consiste de várias linhas contendo um número positivo K (K 1000000). Saída Seu código deve escrever uma linha de saída contendo 3 inteiros separados por espaços. O primeiro inteiro é o tamanho do múltiplo, o segundo é a quantidade de 3s e o terceiro o número de 0s no seu múltiplo. Exemplo de entrada 4 7 14 Exemplo de Saída 3 1 2 6 6 0 7 6 1 7

Problema G (Valladolid 11879) Multiple of 17 Theorem: If you drop the last digit d of an integer n (n 10), subtract 5d from the remaining integer, then the difference is a multiple of 17 if and only if n is a multiple of 17. For example, 34 is a multiple of 17, because 3-20=-17 is a multiple of 17; 201 is not a multiple of 17, because 20-5=15 is not a multiple of 17. Given a positive integer n, your task is to determine whether it is a multiple of 17. Input There will be at most 10 test cases, each containing a single line with an integer 10 100 ). The input terminates with n = 0, which should not be processed. n ( 1 n Output For each case, print 1 if the corresponding integer is a multiple of 17, print 0 otherwise. Sample Input 34 201 2098765413 1717171717171717171717171717171717171717171717171718 0 Sample Output 1 0 1 0 8

Problema H (Valladolid 1431) Cryptography Reloaded What do researchers working at ICPC (Institute for Cryptographic Programming and Computing) do for fun? Well, as you probably have expected, in addition to solving algorithm-related problems on online judges, they also like to toy with various cryptographic schemes. Recently one of the researchers, Tom, has become interested in RSA algorithm implementations used in handheld devices. Note that the description of the general RSA algorithm is as follows: 1) Choose two distinct prime numbers p and q, and let n = pq ; 2) Choose an integer e such that gcd( e,( p - 1)( q - 1)) = 1 ; 3) Compute the integer d that satisfies the congruence relation de 1( mod( p - 1)( q - 1)). Then, if person A wants to give person B a way to send an encrypted message to him, A can follow the above steps and release ( n, e ) as his public key. Upon receiving A's public key, B can simply encrypt message x (0 x < n ) by computing y = x e mod n. This would result in a message which ideally only A could decrypt with his private key d : x = y d mod n. As the computation power of handheld devices is usually limited, a relatively small e is usually used to encrypt data. However this can lead to great security risks. For example, it is quite simple to recover p and q (i.e., factor n ) when you have both the public key ( n, e ) and the private key d. Could you help Tom write a program to demonstrate this? Input There are multiple test cases in the input file. Each test case contains three integers, n, d, and e ( n 10 100, 3 e 31 ). All three integers are given without any preceding zeros. It is guaranteed that all numbers satisfy the condition as given in the problem statement. Two successive test cases are separated by a blank line. A case with n = 0, d = 0 and e = 0 indicates the end of the input file, and should not be processed by your program. Output For each test case, please print two prime numbers, p and q, such that n = pq and p < q, in the format as illustrated below. Sample Input 55 27 3 290203 168101 5 0 0 0 Sample Output Case #1: 5 11 Case #2: 29 10007 9

Problema I (Valladolid 10104) Problema de Euclides O Problema Sabe-se, a partir de Euclides, que, para dois inteiros positivos A e B existem os inteiros X e Y tal que AX+BY=D, onde D é o maximo divisor comum de A e B. O problema é encontrar X, Y and D, dados A e B. Entrada A entrada consiste de um conjunto de linhas com os números inteiros A e B, separados por espaço ( A,B<1000000001 ). Saída Para cada linha de entrada, a saída deve conter três inteiros X, Y e D, separados por espaço. Se houver vários X e Y, você deve imprimir o par para o qual X + Y é mínimo, primariamente e X<=Y (secundariamente). Exemplo de entrada 4 6 17 17 Exemplo de Saída -1 1 2 0 1 17 10

Problema J(Valladolid 12799) RSA RSA is one of the most used cryptographic algorithms and it is considered to be one of the most secure existing alternatives. Its basic operation is described below. Two odd prime numbers p and q are chosen and n=pq is computed. Then the totient function φ(n) = (p-1)(q-1) is computed and an integer e satisfying 1 <e <φ(n) is chosen so that gcd(φ(n),e) = 1. Finally the integer d, the inverse multiplicative of e module φ(n) is computed, that is, the integer d satisfying de 1 mod φ(n). In that way we obtain the public key, which consists of the pair of integers n and e, and the secret key, containing the integers n and d. To encrypt a message m, with 0< m < n, we calculate c = m e mod n, and c is the encrypted message. To decrypt the message, that is, to recover the original message, it suffices to compute m = c d mod n. Note that, in order to do that, the secret key must be known; knowing the public key is not enough to decrypt the message. In this problem your task is to break the RSA cryptography. Input The input contains several test cases. A test case consists of one line, which contains three integers N, E, and C, where 15 N 10 9, 1 E<N and 1 C < N, such that N and E constitute the RSA public key described above, and C is a message encrypted with that public key. Output For each test case in the input your program must produce a single line, containing a single integer M, 1 M <N, the original message. Sample Input 1073 71 436 91 43 19 Sample Output 726 33 11