Simples gerador de números primos
Publicado por Perfil removido (última atualização em 28/03/2018)
[ Hits: 4.105 ]
Um código simples, com algorítimo não otimizado, para gerar números primos em "ranges" passados como parâmetros. O "output" é organizado em colunas, usando o caractere '\t' como separador e quebrando a linha quando atingido 80 colunas.
Exemplo de uso (considerando o nome do binário como "a.out"):
$ ./a.out 1 100
/* This is free and unencumbered software released into the public domain. */ #include <sys/types.h> #include <err.h> #include <errno.h> #include <limits.h> #include <stdio.h> #include <stdlib.h> #define COLUMNS 80 #define SAFEZON 8 #ifndef __progname extern char *__progname; #endif #ifndef getprogname #define getprogname( ) __progname #endif #ifndef setprogname #define setprogname(x) __progname = x #endif static int numlen(ssize_t num) { ssize_t res; for (res = 0; num; res++) num /= 10; return res; } static ssize_t strtobase(const char *str, ssize_t min, ssize_t max, int base) { ssize_t res; char *end; errno = 0; res = strtoll(str, &end, base); if (end == str || *end != '\0') errno = EINVAL; if (res > max || res < min) errno = ERANGE; if (errno) err(1, "strtobase %s", str); return res; } static void usage(void) { fprintf(stderr, "usage: %s from to\n", getprogname()); exit(1); } int main(int argc, char *argv[]) { ssize_t i, from, to; int chrp, ndiv; setprogname(argv[0]); argc--, argv++; if (argc < 2) usage(); from = strtobase(argv[0], 1, SSIZE_MAX, 10); to = strtobase(argv[1], 1, SSIZE_MAX, 10); chrp = 1; for (; from < to; from++) { i = 1; ndiv = 0; for (; i < from; i++) { if (!(from % i) && (i != 1 && i != from)) { ndiv++; break; } } if (ndiv) continue; if ((chrp += numlen(from) + SAFEZON) > COLUMNS) { putchar('\n'); chrp = 1; } printf("%zd", from); if ((from + 1) < to) putchar('\t'); } putchar('\n'); return 0; }
Método de Power para calcular o autovelor dominante de uma matriz
Lista Duplamente Encadeada em C
Resolver problemas de Internet
Como compartilhar a tela do Ubuntu com uma Smart TV (LG, Samsung, etc.)
Descritores de Arquivos e Swappiness
Solução rápida para o problema do Network Manager conectar mas não navegar
Como instalar no Linux Jogos da Steam só para Windows
Instalando o Team Viewer no Debian Trixie - problema no Policykit
Como corrigir o erro chave publica virtual box (2)
Qual driver da NVIDIA instalar? (4)