prime numbers of given range in c using loops only - c

how can i write a program which going to give all prime no of given range WITHOUT using ANY conditions (using just loops!) in c language. i tried many different options but non of them works properly...
for instance:
what i have already tried:
#include <stdlib.h>
#include <stdio.h>
#define UNTIL 1000
#define NOT_INCLUDED 2
int main()
{
int prime =1, i =1,factor=0;
for(prime=1;UNTIL>=prime ;prime++)
{
for( i=1;i<=prime;i++)
{
for(;prime%i==0;)
{
factor++;
}
}
for(;factor==2;factor=0)
{
printf("prime number: %d \n",prime);
}
}
return 0;
}

Challenge accepted: no conditions, hidden or otherwise
#include <stdio.h>
#include <stdlib.h> // atoi
int main(void) {
const char *p = "2 3 5 7 11 13 17 19 23 29\0\0\0\0\0"; /* extend at will */
for (;;) {
p += printf("%d ", atoi(p));
fflush(stdout);
int z = 42 / *p;
(void)z; /* unused warning */
}
return 0;
}
see code running on ideone.com

To check if N is prime, iterate through all the numbers from 2 to N to see if N is divisible by any other number. Every number is divisible by 1, so when you are testing numbers for prime, start testing against 2.
Example
#include <stdio.h>
int is_prime(int N)
{
//0 and 1 are not primes
if (N < 2)
return 0;
//start testing against 2
for(int i = 2; i < N; i++)
if(N % i == 0)
return 0; //not a prime
return 1; //prime
}
int main()
{
printf("Primes from 0 to 1000:\n");
for(int i = 0; i < 1000; i++)
if(is_prime(i))
printf("%d, ", i);
printf("\n");
return 0;
}
You can optimize the loop by changing the range to N/2.
for(int i = 2; i <= N/2; i++)
if(N % i == 0)
return 0; //not a prime
return 1;//prime

Related

A code made to tell if a number is "Perfect Number"

This is a code I wrote in C to find if a given number is a Perfect number or Not.
A Perfect number is a number that is the sum of all its factors.
EXAMPLE - 6
6 has factors 2 , 3 and 1 (1 because it divisible by itself)
and 2 + 3 + 1 = 6
#include <stdio.h>
int main(){
int number;
int sum =0,i;
scanf("%d",&number);
for(i=0;i<number;i++){
if(number % i==0){
sum += i;
}else{ sum = sum;}
}if(sum==number){
printf("Perfect Number");
}else{
printf("Not a Perfect Number");
}
return 0;
}
The code is logically correct and its suppose to give the right output but the problem is that it is not giving any output.
Instead in CLion it terminates with a code " Process finished with exit code -1073741676 (0xC0000094)"
Your loop must have i to start from 1, not 0, otherwise you'll have division by zero when you do number % i == 0:
#include <stdio.h>
int main(void) {
int number;
int sum = 0;
printf("Insert number: ");
scanf("%d", &number);
// NOTE: replaced condition `i < number` with `i <= number / 2`
// for improved performance
for (int i = 1; i <= number / 2; i++) {
if (number % i == 0) {
sum += i;
}
}
if (sum == number) {
printf("Perfect Number\n");
}
else {
printf("Not a Perfect Number\n");
}
return 0;
}
Here is a solution with Cyclomatic Complexity of 2. I don't see a reason for this, but you can do it.
#include <stdio.h>
int main(void)
{
int number = 33550336;
int sum = 0;
for(int i = 1; i <= number / 2; i++) {
sum += i * (number % i == 0);
}
printf("%d is %s", number, "not a perfect number." + 4 * (sum==number));
return 0;
}
Function version:
#include <stdio.h>
#include <stdbool.h>
bool is_perfect(int number)
{
int sum = 0;
for(int i = 1; i <= number / 2; i++) {
sum += i * (number % i == 0);
}
return sum == number;
}
int main(void)
{
int n = 33550336;
printf("%d is %s", n, "not a perfect number." + 4 * is_perfect(n));
return 0;
}
The best version is this one with Cyclomatic Complexity of 1:
bool is_perfect(int n)
{
return n == 6 || n == 28 || n == 496 || n == 8128 || n == 33550336;
}
Much faster! 😅

C program to find the trailing ZEROS at the end of a FACTORIAL of a given number

I have return the code to find a factorial and to display trailing zeros at the end of the factorial, but the output is wrong... could you please help me to find the mistake?
#include <stdio.h>
int main() {
int m = 1, i, N, count = 0;
scanf("%d", &N);
for (i = 1; i <= N; i++) {
m = m * i;
}
printf("%d", m);
while (m > 0) {
if ((m % 10) == 0) {
count = count + 1;
m = m / 10;
}
break;
}
printf("%d", count);
return 0;
}
Your code only works for very small values of N: up to 9. For slightly larger values, you would need to add an else keyword before the break statement and you would get a correct result for a few more cases.
For larger values, you must compute the power of 5 that divides the factorial. You can do this incrementally by summing the power of 5 that divide each individual number up to and including N.
#include <stdio.h>
int main() {
int N, count;
if (scanf("%d", &N) != 1)
return 1;
/* only consider factors that are multiples of 5 */
count = 0;
for (int i = 5; i <= N; i += 5) {
for (int j = i; j % 5 == 0; j /= 5)
count++;
}
printf("%d\n", count);
return 0;
}
An even simpler and faster solution is this: compute the number of multiples of 5 less or equal to N, add the number of multiples of 5*5, etc.
Here is the code:
#include <stdio.h>
int main() {
int N, count;
if (scanf("%d", &N) != 1)
return 1;
count = 0;
for (int i = N; (i /= 5) > 0;) {
count += i;
}
printf("%d\n", count);
return 0;
}
you have two problems
your collapse the two outputs so you see only one of them / you cannot see who is who, just add a separator between them
an else is missing when you count so you count to only up to 1 and the result is wrong from factorial 10
So the minimal changes produce :
int main()
{
int m=1,i,N,count=0;
scanf("%d",&N);
for(i=1;i<=N;i++)
{
m=m*i;
}
printf("%d\n",m); /* <<< added \n */
while(m>0)
{
if((m%10)==0)
{
count=count+1;
m=m/10;
}
else /* <<< added else */
break;
}
printf("%d\n",count); /* <<< added \n */
return 0;
}
after the changes :
pi#raspberrypi:/tmp $ ./a.out
5
120
1
pi#raspberrypi:/tmp $ ./a.out
10
3628800
2
Of course that supposes first you are able to compute the factorial without overflow
I also encourage you to check a value was read by scanf, checking it returns 1
#include <stdio.h>
int main()
{
int n,i,f=1,t,c=0;
printf("Enter number ");
scanf("%d",&n);
t=n;
for(i=1;t>=5;i++)
{
t=n/5;
c=c+t;
n=t;
}
printf("number of zeros are %d",c);
return 0;
}

for loop unexpectedly jumping down in value

Goldbach's conjecture states that every even integer over 4 is the sum of two primes, I am writing a program in C to find these pairs. To do this it first finds all the primes less than a user given number. I have a for loop to iterate from 4 to the user given number and find the pairs within the loop body. When that loop gets to about around 40, suddenly jumps back down by about 30 and then continues to iterate up (with user input 50 it jumped from 38 to 9, with input 60 it jumped from 42 to 7). I can't figure out why this is happening. Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <sys/types.h>
#include <unistd.h>
struct pair{
int a;
int b;
}pair_t;
int main(){
int N;
int numPrimes = 1;
int *primes = malloc(100*sizeof(int));
int isPrime = 1;
primes[0] = 2;
int timesRealloc = 0;
int availableSlots = 100;
printf("Please enter the largest even number you want to find the Goldbach pair for: \n");
scanf("%d", &N);
struct pair pairs[N/2 + 4];
int j = 0;
int i;
for (i = 3; i <= N; i+=2){
j = 0;
isPrime = 1;
while (primes[j] <= sqrt(i)) {
if (i%primes[j] == 0) {
isPrime = 0;
break;
}
j++;
}
if (isPrime == 1){
primes[numPrimes] = i;
numPrimes++;
}
if (availableSlots == numPrimes){
timesRealloc++;
availableSlots += 100;
primes = realloc(primes, availableSlots*sizeof(int));
}
}
printf("The largest prime I found was %d\n", primes[(numPrimes-1)]);
int k;
for (i=4; i<=N; i+=2){
printf("i is %d, N is %d\n", i, N);
if (i > N){ break; }
for (j=0; j<numPrimes; j++){
for (k=0; k<numPrimes; k++){
int sum = primes[j] + primes[k];
if(sum == i){
pairs[i].a = primes[j];
pairs[i].b = primes[k];
}
}
}
}
for (i=4; i<=N; i+=2){
printf("%d is the sum of %d and %d\n", i, pairs[i].a, pairs[i].b);
}
return 0;
}
You attempt to be space efficient by compressing the pairs array to just hold every other (even) number and start from 4 instead of zero. However, you miscalculate its size and then when you go to use it, you treat it like it hasn't been compressed and that there's a slot for every natural number.
The code suffers from having the prime array calculation in main() along with the other code, this is best separated out. And when it looks for pairs, it doesn't quit when it finds one, nor when it starts getting sums greater than the target. My rework below attempts to address all of these issues:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdbool.h>
#define INITIAL_SLOTS (100)
struct pair {
int a;
int b;
} pair_t;
int compute_primes(int limit, unsigned **primes, int size) {
int numPrimes = 0;
(*primes)[numPrimes++] = 2;
for (int i = 3; i <= limit; i += 2) {
bool isPrime = true;
for (int j = 0; (*primes)[j] <= i / (*primes)[j]; j++) {
if (i % (*primes)[j] == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
(*primes)[numPrimes++] = i;
}
if (numPrimes == size) {
size *= 2;
*primes = realloc(*primes, size * sizeof(unsigned));
}
}
return numPrimes;
}
int main() {
int N;
printf("Please enter the largest even number you want to find the Goldbach pair for: \n");
scanf("%d", &N);
unsigned *primes = calloc(INITIAL_SLOTS, sizeof(unsigned));
int numPrimes = compute_primes(N, &primes, INITIAL_SLOTS);
printf("The largest prime I found was %d\n", primes[numPrimes - 1]);
struct pair pairs[(N - 4) / 2 + 1]; // compressed data structure
for (int i = 4; i <= N; i += 2) {
int offset = (i - 4) / 2; // compressed index
bool found = false;
for (int j = 0; ! found && j < numPrimes; j++) {
for (int k = 0; ! found && k < numPrimes; k++) {
int sum = primes[j] + primes[k];
if (sum == i) {
pairs[offset].a = primes[j];
pairs[offset].b = primes[k];
found = true;
} else if (sum > i) {
break;
}
}
}
}
for (int i = 4; i <= N; i += 2) {
int offset = (i - 4) / 2; // compressed index
printf("%d is the sum of %d and %d\n", i, pairs[offset].a, pairs[offset].b);
}
free(primes);
return 0;
}
OUTPUT
> ./a.out
Please enter the largest even number you want to find the Goldbach pair for:
10000
The largest prime I found was 9973
4 is the sum of 2 and 2
6 is the sum of 3 and 3
8 is the sum of 3 and 5
10 is the sum of 3 and 7
12 is the sum of 5 and 7
14 is the sum of 3 and 11
...
9990 is the sum of 17 and 9973
9992 is the sum of 19 and 9973
9994 is the sum of 53 and 9941
9996 is the sum of 23 and 9973
9998 is the sum of 31 and 9967
10000 is the sum of 59 and 9941
>

Create a dice chart

I am facing a problem right now and can't seem to solve it. Whenever I start my code I get a segmentation fault. My aim is to roll two dice. The value is generated by a random number. I want to roll 10000 times and save the values within an array, so I can create a little chart at the end which will show the diced the values. I appreciate any help and hints on how to solve the problem. Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define DICE 2
#define DICEEYES (DICE * 6) -DICE +1
#define COUNT 10000
int diceRoll(int dice);
int main(void)
{
srand(time(0));
int valuesOfRoll[DICEEYES] = { 0 };
for(int i = 0; i < COUNT; i++)
{
int index = diceRoll(DICE) - DICE;
valuesOfRoll[index]++;
}
for(int i = 0; i < DICEEYES; i++)
{
if(valuesOfRoll[i] < 1) continue;
printf("The number %2d was rolled %4d times\r\n", i + DICE, valuesOfRoll[i]);
}
return 0;
}
int diceRoll(int dice)
{
int sum;
for(int i = 0; i < dice; i++)
{
sum += rand() % 6 + 1;
}
return sum;
}
You should initialize sum in the function diceRoll(),
/* always return value between [dice..dice*6]*/
int diceRoll(int dice)
{
int sum=0;
for(int i = 0; i < dice; i++)
{
sum += rand() % 6 + 1;
}
return sum;
}
Since sum could have any value (on the stack), you were using an index value that could fall outside the ValuesOfRoll[] array. One way to avoid is to use the modulus operator to limit the returned index to a valid range.
int main(void)
{
srand(time(0));
int valuesOfRoll[DICEEYES] = { 0 };
for(int i = 0; i < COUNT; i++)
{
int index = diceRoll(DICE) - DICE;
/* limit index to [0..DICEEYES] */
index %= DICEEYES;
valuesOfRoll[index]++;
}
for(int i = 0; i < DICEEYES; i++)
{
if(valuesOfRoll[i] < 1) continue;
printf("The number %d was rolled %4d times", i + DICE, valuesOfRoll[i]);
}
return 0;
}
Initialise the value of sum in your function (preferably to 0), otherwise it will hold some garbage value.
int diceRoll(int dice)
{
int sum;
for(int i = 0; i < dice; i++)
{
sum += rand() % 6 + 1;
}
return sum;
}
The garbage value may be a very large number, and so will be the returned value of the function. So, when the returned value is used in this line:
int index = diceRoll(DICE) - DICE;
then the array will have an index of that large number, valuesOfRoll[some_large_integer]++;. This causes an out-of-array-bound situation, and causes seg-fault.
Slightly belatedly, the faults are not initialising sum, and DICEEYES.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define DICE 2
#define DICEEYES (DICE * 6)
#define COUNT 10000
int diceRoll(int dice)
{
int i, sum = 0; // need to initialise!
for(i = 0; i < dice; i++)
sum += rand() % 6 + 1;
return sum;
}
int main(void)
{
int i;
int valuesOfRoll[DICEEYS+1] = { 0 }; // size of array
srand((unsigned)time(0));
for(i = 0; i < COUNT; i++)
valuesOfRoll[diceRoll(DICE)]++;
for(i = DICE; i <= DICEEYES; i++)
printf("The number %2d was rolled %4d times\n", i, valuesOfRoll[i]);
return 0;
}
Program output:
The number 2 was rolled 264 times
The number 3 was rolled 573 times
The number 4 was rolled 798 times
The number 5 was rolled 1145 times
The number 6 was rolled 1373 times
The number 7 was rolled 1697 times
The number 8 was rolled 1385 times
The number 9 was rolled 1143 times
The number 10 was rolled 835 times
The number 11 was rolled 528 times
The number 12 was rolled 259 times
the following code
1) cleanly compiles
2) has corrections to the output formatting
3) properly initializes values (good case for always initialize all values)
4) outputs the proper data
5) does not try to fiddle offset/indexes, etc
6) uses meaningful #define names, function parameter names, etc
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define NUM_DICE (2)
#define NUM_ROLLS (10000)
#define MIN_DICEROLL_VALUE (2)
#define MAX_DICEROLL_VALUE (12)
int diceRoll(int numDice);
int main(void)
{
srand(time(NULL));
int valuesOfRoll[MAX_DICEROLL_VALUE+1] = { 0 }; // notice the +1
for(int i = 0; i < NUM_ROLLS; i++)
{
int index = diceRoll(NUM_DICE);
valuesOfRoll[index]++;
}
for(int i = MIN_DICEROLL_VALUE; i <= MAX_DICEROLL_VALUE; i++)
{
// 2d for values 2...12 5d for values 0...10000 \n so each output on anew line
printf("The number %2d was rolled %5d times\n", i, valuesOfRoll[i]);
}
return 0;
} // end function: main
int diceRoll(int numDice)
{
int sum = 0; // be sure to initialize value
for(int i = 0; i < numDice; i++)
{
sum += (rand() % 6) + 1;
}
return sum;
} // end of function: diceRoll

How to find the sum of Prime Numbers in C within a given range?

I'm very new to programming and I was asked to find the sum of prime numbers in a given range, using a while loop. If The input is 5, the answer should be 28 (2+3+5+7+11). I tried writing the code but it seems that the logic isn't right.
CODE
#include <stdio.h>
int main()
{
int range,test;
int sum = 2;
int n = 3;
printf("Enter the range.");
scanf("%i",range);
while (range > 0)
{
int i =2;
while(i<n)
{
test = n%i;
if (test==0)
{
goto end;
}
i++;
}
if (test != 0)
{
sum = sum + test;
range--;
}
end:
n++;
}
printf("The sum is %i",sum);
return 0;
}
It would be nice if you could point out my mistake and possibly tell me how to go about from there.
first of all, in the scanf use &range and not range
scanf("%i",&range);
Second this instruction is not correct
sum = sum + test;
it should be
sum = sum + n;
and also the
while (range > 0)
should be changed to
while (range > 1)
Because in your algorithm you have already put the first element of the range in the sum sum = 2 so the while should loop range - 1 times and not range times
That's all
OK, my C is really bad, but try something like the following code. Probably doesn't compile, but if it's a homework or something, you better figure it out yourself:
UPDATE: Made it a while loop as requested.
#include <stdio.h>
int main()
{
int range, test, counter, innerCounter, sum = 1;
int countPrimes = 1;
int [50] primesArray;
primesArray[0] = 1;
printf("Enter the range.");
scanf("%i",range);
counter = 2;
while (counter <= range) {
for (innerCounter = 1; innerCounter < countPrimes; innerCounter++) {
if (counter % primesArray[innerCounter] == 0)
continue;
primesArray[countPrimes + 1] = counter;
countPrimes ++;
sum += counter;
}
counter ++
}
printf("The sum is %i",sum);
return 0;
}
I haven't done C in a while, but I'd make a few functions to simplify your logic:
#include <stdio.h>
#include <math.h>
int is_prime(n) {
int i;
for (i = 2; i <= sqrt(n); i++) {
if (n % i == 0) {
return 0;
}
}
return 1;
}
int main() {
int range, i, sum, num_primes = 0;
printf("Enter the range: ");
scanf("%d", &range);
for (i = 2; num_primes < range; i++) {
if (is_prime(i)) {
sum += i;
num_primes++;
}
}
printf("The sum is %d", sum);
return 0;
}
Using goto and shoving all of your code into main() will make your program hard to debug.
Copy - pasted from here.
#include <stdio.h>
int main() {
int i, n, count = 0, value = 2, flag = 1, total = 0;
/* get the input value n from the user */
printf("Enter the value for n:");
scanf("%d", &n);
/* calculate the sum of first n prime nos */
while (count < n) {
for (i = 2; i <= value - 1; i++) {
if (value % i == 0) {
flag = 0;
break;
}
}
if (flag) {
total = total + value;
count++;
}
value++;
flag = 1;
}
/* print the sum of first n prime numbers */
printf("Sum of first %d prime numbers is %d\n", n, total);
return 0;
}
Output:
Enter the value for n:5
Sum of first 5 prime numbers is 28
Try the simplest approach over here. Check C program to find sum of all prime between 1 and n numbers.
CODE
#include <stdio.h>
int main()
{
int i, j, n, isPrime, sum=0;
/*
* Reads a number from user
*/
printf("Find sum of all prime between 1 to : ");
scanf("%d", &n);
/*
* Finds all prime numbers between 1 to n
*/
for(i=2; i<=n; i++)
{
/*
* Checks if the current number i is Prime or not
*/
isPrime = 1;
for(j=2; j<=i/2 ;j++)
{
if(i%j==0)
{
isPrime = 0;
break;
}
}
/*
* If i is Prime then add to sum
*/
if(isPrime==1)
{
sum += i;
}
}
printf("Sum of all prime numbers between 1 to %d = %d", n, sum);
return 0;
}

Resources