Write functions that :
- reads and return a positive integer
- checks whether an integer is prime or not
- generates the first N primes numbers
- generates the prime factors of an integer
Difficulty level
This exercise is mostly suitable for students
#include<stdio.h>
#include<conio.h>
#include<math.h>
#define N 100
int isprime(int nb)
{
int i;
for (i = 2; i <= sqrt(nb); i++)
if (nb%i == 0)
return 0;
return 1;
}
int read()
{
int n;
do {
printf("Enter a nb: ");
scanf("%d", &n);
} while (n <= 1);
return n;
}
void listofprimes(int A[])
{
int i, count;
count = 0;
i = 2;
while (count < N)
{
if (isprime(i))
{
A[count] = i;
//printf("%d ", i);
count++;
}
i++;
}
}
void print_array(int a[], int S)
{
int i;
for (i = 0; i < S; i++)
printf(" %d \t %d \n", i, a[i]);
printf("\n\n\n");
}
void print_array2(int a[], int b[], int S)
{
int i;
for (i = 0; i < S - 1; i++)
{
if (b[i] > 1)
printf(" %d ^ %d x", a[i], b[i]);
else
printf(" %d x", a[i]);
}
if (b[i]>1)
printf(" %d ^ %d.", a[i], b[i]);
else
printf(" %d.", a[i]);
printf("\n\n\n");
}
int prime_factors(int nb, int primes[], int factors[])
{
int counterinprime = 0, nbfactor = 0;
while (nb > 1)
{
if (nb%primes[counterinprime] == 0)
{
factors[nbfactor] = primes[counterinprime];
nbfactor++;
nb = nb / primes[counterinprime];
counterinprime = 0;
}
else
counterinprime++;
}
return nbfactor;
}
int pm(int f[], int sf, int dist[], int occ[])
{
int i, j;
int count;
dist[0] = f[0];
occ[0] = 1;
count = 1;
for (i = 1; i < sf; i++)
{
for (j = 0; j < count; j++)
{
if (f[i] == dist[j])
{
occ[j]++;
break;
}
}
if (j == count)
{
dist[j] = f[i];
occ[j] = 1;
count++;
}
}
return count;
}
void main()
{
int nb;
int result;
int primes[N];
int factors[N], size;
int dist[N], occ[N], s2;
nb = read();
//result = isprime(nb);
/*if (result != 0)
printf("%d is prime\n", nb);
else
printf("%d is not prime\n", nb);
*/
listofprimes(primes);
//print_array(primes,N);
size = prime_factors(nb, primes, factors);
//print_array(factors,size);
s2 = pm(factors, size, dist, occ);
printf("%d =", nb);
print_array2(dist, occ, s2);
getch();
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Implement a stack using a heap