Getting all prime numbers between 2 and 100 in C - c

This is my code which is supposed to output prime numbers only.
#include <stdio.h>
int prime(int n){
int j;
for (j=2;j<=n/2;j++){
if((n%j)==0){
return 0;
}
else{
return 1;
}
}
}
void main(){
int i,p;
for (i=2;i<=100;i++){
p=prime(i);
if(p==1){
printf("%d \n",i);
}
}
}
The result is 2,3,7,9,11,13,15....
not 2,3,5,7,11,13....
What did I do wrong?

Your probably want:
int prime(int n){
int j;
for (j=2;j<=n/2;j++)
if((n%j)==0)
return 0;
return 1;
}

Prime Numbers are numbers which are only divisible by two numbers. eg 2,3,5,7,11 etc.
int main()
{
int i,j,n=0;
for(i=2;i<=100;i++)
{
for(j=1;j<=i;j++)
{
if(i%j==0)
{
n++;
}
}
if(n==2)
printf("%d\n",i);
n=0;
}
getch();
}

Try this :
int prime(int n){
int j;
int isPrime = 1;
for (j=2;j<=n/2;j++){
if((n%j)==0){
isPrime = 0;
break;
}
}
return isPrime;
}

If you're trying to find out Prime numbers up to a given number(in your case 2..100) building a prime table will speed up the process:
NOTE: it's important that inputs are sequential to help build prime table.
#include <stdio.h>
#include <math.h>
/* Building a prime table for fast look up
* NOTE : Numbers should be input from 2 to n in a sequential pattern to help build prime table; */
# define PRIME_TAB_MAX 200
int prime_specific(int num)
{
static int primeTab[PRIME_TAB_MAX] = { 0, };
static int primeCount = 0;
int check_limit ;
unsigned int idx;
if (num < 2)
return 0;
if (primeCount > 0) {
check_limit = (int)sqrt(num);
for (idx = 0; idx < primeCount && primeTab[idx] <= check_limit; idx++) {
if (0 == (num % primeTab[idx])) {
return 0;
}
}
}
else {
for (idx = 2; idx <= num / 2; idx++)
if (0 == (num % idx))
return 0;
}
if (primeCount < PRIME_TAB_MAX) {
primeTab[primeCount++] = num;
return 1;
}
else {
fprintf(stderr, "\nERROR: Prime Table is full");
return (-1); //Internal error
}
}
int main(void)
{
unsigned int idx;
int status ;
for (idx = 2; idx <= 1000; idx++) {
status = prime_specific(idx);
switch (status)
{
case 1:
fprintf(stderr, "%d\n", idx);
break;
case 0:
//Do nothing
break;
default:
fprintf(stderr, "\nERROR:Internal Error");
return (-1);
}
}
return 0;
}

Code:
#include <stdio.h>
int main ()
{
/* local variable definition */
int i, j;
for(i=2; i<100; i++)
{
for(j=2; j <= (i/j); j++)
if(!(i%j)) break; // if factor found, not prime
if(j > (i/j)) printf("%d is prime\n", i);
}
return 0;
}

Related

Optmize a program to count the number of prime number pairs whose sum is equal to one number N (N <1,000,000)

I have written a piece of code below, that ask a user input a number N (3 < N < 1.000.000) odd and count the number of prime number pairs whose sum is equal to N. That code works, but I need to optmize it to make more efficient. When the user inputs a number, I count the number of primes up to this number and store each prime number in a vector, and after that count the number of prime number pairs whose sum is equal to this input.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void seleciona_primos (int *vet, int n, int raiz){
int i, j;
vet[2] = 2;
for(i=3; i<=n; i+=2){
vet[i] = i;
}
for (i=3; i<= raiz; i+=2){
if(vet[i]!=0){
for(j=3; j<=n; j+=2){
if ((vet[i]!=vet[j]) && (vet[j]%vet[i] == 0)){
vet[j]=0;
}
}
}
}
}
int conta_pares (int *vet, int n){
int i, j, count=0;
for (i=3; i<=n; i+=2){
if(vet[i]!=0){
for(j=3; j<=n/2; j+=2){
if((vet[j]!=0) && (vet[i] + vet[j] == n)&& (vet[i]!=0)){
//printf("%d ", vet[i]);
//printf("%d\n", vet[j]);
count++;
vet[i] = 0;
}
}
}
}
if(vet[n-2]!=0){
count++;
}
return count;
}
int main()
{
int *vet, n, raiz, i , count;
scanf("%d", &n);
vet = (int *) calloc((n+1), sizeof(int));
raiz = floor(sqrt(n));
seleciona_primos(vet, n, raiz);
count = conta_pares(vet, n);
printf("%d",count);
//for(i=3; i<=n; i+=2){
//if(vet[i]!=0){
//printf("%d\n", vet[i]);
//}
//}
return 0;
}
I make an array who countain the prime numbers from 2 to N(1 has only one divisors and 0 has infinites of divisors), and then I check if two numbers from the array equal to N
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
bool Prime(int);
int main()
{
long N;
do
{
printf("Give me the number of numbers :");
scanf("%ld",&N);
}while(N<=4||N>1000000);//N must be between 3 & 1000000
int prime[N];
int arr[N];
int j=0;
for(int i=2;i<N;i++)
{
if(Prime(i)==true)
{
prime[j]=i;
j++;
}
}
printf("\n\n");
for(int p=0;p<j-1;p++)
{
for(int q=p+1;q<j;q++)
{
if(N==prime[p]+prime[q])
{
printf("\n%d = %d + %d \n",N,prime[p],prime[q]);
}
}
}
printf("\n\n");
return 0;
}
bool Prime(int n)
{
for(int i=2;i<=(n/2);i++)
{
if(n%i==0)
{
return false;
}
}
return true;
}
Example :
Input : N =100;
Output :
100 = 3 + 97
100 = 11 + 89
100 = 17 + 83
100 = 29 + 71
100 = 41 + 59
100 = 47 + 53
Thank you for all suggestions!!
And after some research and tries, I have found the solution that follow bellow:
int isPrime(int x)
{
int i;
for(i = 2; i <= sqrt(x); i++)
{
if(x%i == 0)
{
return 0;
}
}
return 1;
}
int main()
{
int i, count = 0, n ;
scanf("%d", &n);
for(i = 3; i <= n/2 ; i+=2)
{
if(isPrime(i))
{
if((isPrime(n-i)))
{
count++;
}
}
}
if(isPrime(n-2))
{
count++;
}
printf("%d", count);
return 0;
}
I modified your code to optimize it, I have set two Boolean vectors one for 5 mod(6) prime numbers (vet1[i]=false corresponds to prime number 6 x i-1 es. i=1 corresponds to prime number 5=6 x 1-1) and one (vet2[i]corresponds to prime number 6 x i+1) for prime numbers 1 mod(6)
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdbool.h>
void seleciona_primos (bool *vet1, bool *vet2,int n){
int i, i1,imax;
imax=(n-n%6)/6+1;
for (i=1; (6*i-1)*(6*i-1) <=n; i++){
if (vet1[i]==false){
for(int i1 = 6*i*i; i1 <= imax+2*i; i1 += (6*i-1)){
if(i1<imax)
vet1[i1]=true;
vet2[i1-2*i]=true;
}
}
if (vet2[i]==false){
for(int i1 = 6*i*i; i1 <= imax; i1 += (6*i+1)){
vet1[i1]=true;
if(i1<imax-2*i)
vet2[i1+2*i]=true;
}
}
}
}
int conta_pares (bool *vet1, bool *vet2, int n){
int i,imax, count=0,r6;
imax=(n-n%6)/6;
r6=n%6;
if (r6==0){
for (i=1; i<imax; i++){
if(vet1[i]== false && vet2[imax-i]== false)
count++;
}
}
if (r6==2){
for (i=1; i<imax; i++){
if(vet2[i]== false && vet2[imax-i]== false)
count++;
}
count=(count+count%2)/2;
}
if (r6==4){
for (i=1; i<=imax; i++){
if(vet1[i]== false && vet1[imax+1-i]== false)
count++;
}
count=(count+count%2)/2;
}
if (r6>0 && r6<3){
if (vet1[imax]==false)
count++;
}
if (r6>2 && r6<5){
if (vet2[imax]==false)
count++;
}
return count;
}
int main()
{
int n, i , count;
bool *vet1, *vet2;
scanf("%d", &n);
vet1 = (bool *) calloc((n-n%6)/6+2, sizeof(bool));
vet2 = (bool *) calloc((n-n%6)/6+2, sizeof(bool));
seleciona_primos(vet1,vet2, n);
count = conta_pares(vet1,vet2, n);
printf("%d",count);
free(vet1);
free(vet2);
return 0;
}

where to put statement for powerful number?

I have make this program that calculates number factorization such as 60 = 2^2 * 5 * 3.
How can i modify my code in order to print POWERFUL NUMBERS such as 9000 = 2^3 * 3^2 * 5^3 without using math.h library and without using arrays?
Thank you very much!!
#include<stdio.h>
#define MAX 1000
int main(){
int num;
int counter;
int number;
char factorizationOutput;
int isAchiles = 0;
int factor=2;
for(counter=2;counter<=MAX;counter++){
isAchiles = 1;
number=counter;
int factor=2;
while(factor<number){
int power=0;
if(number%factor==0){
while(number%factor==0){
number=number/factor;
power++;
}
if(power == 1){
isAchiles = 0;
}
printf("%d^%d",factor,power);
if(number!=1)
printf(" X ");
}
factor++;
}
if(number!=1)
printf("%d^1.\n",factor);
if(isAchiles == 1){
printf("factorazation of number %d is: ",counter);
}
}
}
#include<stdio.h>
int main(void)
{
int n;
scanf("%d", &n);
printf("%d = ", n);
for(int i = 1; i <= n; i++)
{
int count = 0;
for(int j = 1; j <= i; j++)
{
if(i % j == 0)
{
count++;
}
}
int l = 0;
if(count == 2)
{
while(n % i == 0)
{
l++;
n = n/i;
}
printf("%d^%d*", i, l);
}
}
}

Why is my program only taking one input before completing?

This program uses an array and three functions to read inputs, sum up the ones and tens place of inputted integers, and compute the average of input integers. Why can't I get more than one input that is a positive integer? The program runs after one input that is within the limits of integers that are valid.
#include <stdio.h>
int read_data(int Ar[]);
void comp_sums(int Ar[], int size); // prototypes
double comp_avg(int Ar[], int size);
int main()
{
int Ar[100];
int size;
double avg;
size = read_data(Ar);
comp_sums(Ar, size);
avg = comp_avg(Ar, size);
printf("The average of the integers in the array: %lf\n", avg);
}
int read_data(int Ar[]) // reads inputted integers, stores in array
{
int flag;
char ch;
int i,j, num;
flag = 1;
i = 0;
while (flag == 1) {
printf("Please enter an integer:\n");
j = scanf("%d", &num);
if (j != 1) {
break;
}
if (num < 0) {
continue;
} else if (num >= 100) {
flag = 0;
} else {
Ar[i] = num;
i++;
}
return i;
}
}
void comp_sums(int Ar[], int size) /* computes sum of ones and tens place of the inputted integers into the array*/
{
int i, j;
int sum_ones, sum_tens;
sum_ones = 0;
sum_tens = 0;
for (i = 0; i < size; i++) {
sum_ones += Ar[i] % 10;
j = Ar[i] / 10;
sum_tens += j % 10;
}
printf("The sum of the ones is: %d\n", sum_ones);
printf("The sum of the tens is: %d\n", sum_tens);
}
double comp_avg(int Ar[], int size) // computes average of integers
{
int i, sum;
double avg;
sum = 0;
for (i = 0; i < size; i++) {
sum += Ar[i];
}
avg = (double)size / sum;
return avg;
}
When you take an array as an argument, you have to take the length as well,
because you have to check if you are reading/writing out of bounds. Forget for a
second that the return is at that incorrect position, the user can input more
values than the array can hold and you are doing nothing to prevent the buffer overflow.
So to fix your read_data function:
int read_data(int Ar[], size_t len)
{
if(Ar == NULL || len == 0)
return 0;
int i = 0, j, num;
// imortant to check the bounds
while (i < len) {
printf("Please enter an integer:\n");
j = scanf("%d", &num);
if (j != 1) {
break;
}
if (num < 0) {
continue;
} else if (num >= 100) {
break;
} else {
Ar[i] = num;
i++;
}
}
return i;
}
I removed the flag bit because if num >=100, you would be ending the loop
anyway, so it's much simpler to do a break. Also the intention is more clearer.
Now you can call it:
int main()
{
int Ar[100];
int size;
double avg;
size = read_data(Ar, sizeof Ar / sizeof *Ar);
...
}
The problem is that you call return inside the whileloop. So as soon as you get a valid number, you'll return from the function.
Move it outside the loop. Like:
while (flag == 1) {
printf("Please enter an integer:\n");
j = scanf("%d", &num);
if (j != 1) {
break;
}
if (num < 0) {
continue;
} else if (num >= 100) {
flag = 0;
} else {
Ar[i] = num;
i++;
}
// return i; Incorrect
}
return i; // Correct

What's wrong with my Checkprime.c program?

I'm trying to make a program that checks whether a given number is a prime number or not. However, my program just gives me the 2 time table, and I don't know why.
Here is my main class:
#include <stdio.h>
#include "defs.h"
#include "checkprime.c"
int Prime[MaxPrimes];
int main()
{
int UpperBound;
int N;
int *ba = &UpperBound;
printf("enter upper bound\n");
scanf("%d",ba);
Prime[2] = 1;
for (N = 3; N <= *ba; N+= 2)
{
CheckPrime(N);
if (Prime[N]== 1) printf("%d is a prime\n",N);
}
}
Here is my checkprime.c
#include "defs.h"
#include "externs.h"
int CheckPrime(int K)
{
int J;
J = 2;
while (1)
{
if (Prime[J] == 1)
{
if (K % J == 0)
{
Prime[K] = 0;
return 0;
}
J++;
}
break;
}
Prime[K] = 1;
}
There are some problems in CheckPrime with the loop exit conditions. Use the following instead:
int CheckPrime(int K)
{
int J;
for (J=2; J*J <= K; J++) {
if (Prime[J] == 1) {
if (K % J == 0) {
Prime[K] = 0;
return 0;
}
}
}
Prime[K] = 1;
return 1;
}
The rest of it should work with this change.

Accept a number and print its alternate digits,

int Rearrange(int a)
{
long int b,j,i=0,num=0,count=0,arr[100];
while(a>0)
{
b=a%10;a=a/10;
arr[i]=b;
i++;
count ++;
}
j=count;
for(i=0;i<=count/2;i++)
{
t=arr[i];
arr[i]=arr[count-i-1];
arr[count-i-1]=t;
count--;
}
for(i=0;i<j;i+=2)
{
num=num*10 + arr[i]%10;
}
return num;
}
I want to write a function in c rearrange which prints the alternate digits of a number it is given.
for example:
input:- 12345
output:- 135
Thank you
Why complicating a simple problem?
If you don't mind an alternative approach, please check the below code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int input = 0;
int len = 0;
int i = 0;
char sinput[64] = {0, };
printf("Enter the number :");
scanf("%d", &input);
sprintf(sinput, "%d", input);
len = strlen(sinput);
printf("Output : ");
for (i = 0; i < len; i+=2)
{
printf("%c\t", sinput[i]);
}
printf("\n");
return 0;
}
Sample i/o:
[sourav#braodsword temp]$ ./a.out
Enter the number :123456
Output : 1 3 5
[sourav#braodsword temp]$
Your for loops are faulty. Change those to:
for(i=0;i<=count/2;i++)
{
int t=arr[i];
arr[i]=arr[j]; /* Use j */
arr[j]=t; /* Use j */
/* count--; Dont decrement */
j--;
}
for(i=0;i<count;i+=2) /* Should be count */
{
num=num*10 + arr[i]%10;
}
Demo
There can be many alternate ways to solve, but I just want to show you how the approach in thought process can be implemented correctly.
In your code problem is with the first for loop.
Please check the below code.
int Rearrange(int a)
{
long int b = 0, j = 0, i = 0, num = 0, count = 0, arr[100];
while (a > 0)
{
b = a % 10; a = a/10;
arr[i] = b;
i++;
count++;
}
j = count;
for (i = 0; i < count/2; i++) // Condition is problematic
{
long int t = arr[i];
arr[i] = arr[count-i-1];
arr[count - i - 1] = t;
// count--; // this is problamatic.
}
for (i = 0; i < j; i += 2)
{
num = num * 10 + arr[i] % 10;
}
return num;
}
#include<stdio.h>
int main()
{
int n,arr[40];
scanf("%d",&n);
printf("%d",n);
int s=0,i=0;
while(n!=0)
{
arr[i]=n%10;
printf("%d",arr[i]);
n=n/10;
i++;
}
for(int j=i-1;j>=0;j-=2)
{
s =s*10+arr[j];
}
printf("\n%d",s);
return 0;
}
int alternatedigits(int n)
{
int a[10],i=0,count=0,sum=0;
while(n!=0)
{
a[i]=n%10;
i++;
count++;
n=n/10;
}
for(int i=count;i>=0;i++)
{
if(i%2==0)
{
sum=sum*10+a[i];
}
}
return sum;
}

Resources