Finding Prime numbers from 1 to 300 in C - c

I have typed the following program in C language:
#include <stdio.h>
int main ()
{
int i = 1, a = 2;
while (i <= 300)
{
while (a < i)
{
if (i % a == 0)
break;
else
printf ("%d\n", i);
a++;
}
i++;
}
return 0;
}
The program is printing many non-prime values too like 295, 275, etc...
Please help, I'm a beginner and lacks much experience.

Beside the fact that you're not resetting a to 2, the printf() statement is not placed correctly. This will print any number of i that cannot be divided by 2 (even if it can be divided by another number).
Change your code like this:
#include <stdio.h>
int main ()
{
int i = 1, a = 2, is_prime;
while (i <= 300)
{
is_prime = 1;
while (a < i)
{
if (i % a == 0) {
is_prime = 0;
break;
}
a++;
}
if(is_prime)
printf ("%d\n", i);
a = 2;
i++;
}
return 0;
}

You need to set a back to 2 before you enter the loop:
#include <stdio.h>
int main ()
{
int i = 1, a = 2;
while (i <= 300)
{
a = 2; // add this line
while (a < i)
{
if (i % a == 0)
break;
else
printf ("%d\n", i);
a++;
}
i++;
}
return 0;
}
Your method isn't very fast. You should read this page http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

Related

why when I input any number between 14 and 20, the output is incorrect?

'I need to calculate and print an upside down pascal triangle, so I wrote down 2 functions for factorial and for the nCr, and I have followed, the equation x! / (y! * (x - y)!)'
#include <stdio.h>
#include <stdlib.h>
int Factorial (int value)
{
if (value == 1 || value == 0)
{
return 1;
}
return value*Factorial(value - 1);
}
int nCr(int value, int r)
{
return Factorial(value)/(Factorial(r) * Factorial(value - r));
}
int main(int argc, char **argv)
{
int value, i, j, k;
char* p;
value = strtol(argv[1], &p, 10);
if (*p != '\0')
{
return 1;
}
if (argc != 2)
{
return 1;
}
if (value < 1 || value > 20)
{
printf("Error: Please enter a value between 1 and 20 inclusively\n");
return 1;
}
else
'The problem is supposed to be in the nested loops I guess'
{
for (i = value - 1; i >= 0; i--)
{
for (j = value - i; j > 0; j--)
{
printf(" ");
}
for (k = 0; k <= i; k++)
{
printf("%d ", nCr(i, k));
}
printf("\n");
}
}
return 0;
}
The problem was in the declaration of the Factorial functions, as int type would overflow if the input is more than 13!, so we should declare the Factorial function as long, so that it does not overflow.

Is it possible to create a program that accepts 3 integers and outputs the odd/even integers without using array?

Our teacher gave us an exercise in C. We have to create a program that accepts three integers and outputs them if they are odd or even without using arrays, only loops and conditional statements can be used.
What I am only allowed to use are scanf(), printf(), loops and conditional statements. I must not have multiple variables like odd1, odd2, odd3, even1, even2, even3.And I must not do scanf("%d %d %d",), so I must run scanf("%d") three times in a loop.I couldn't think of any idea that would precisely print the same format of the expected output. I hope someone could help me on this
#include <stdio.h>
int main() {
int i, num;
printf("Enter three integers: ");
for(i=1;i<=3;i++)
{
scanf("%d", &num);
if(!(num%2))
{
printf("\nEven: %d", num);
}
if(num%2)
{
printf("\nOdd: %d\n", num);
}
}
}
I expect the following like this...
Input:
1 2 3
Output:
Odd: 1 3
Even: 2
Input:
2 4 6
Output:
Odd:
Even: 2 4 6
...but the only thing i can do is this
Input:
1 2 3
Output:
Odd: 1
Even: 2
Odd: 3
Input:
1 3 5
Output:
Odd: 1
Odd: 3
Odd: 5
Recursion (loop in disguise) for the win (if you don't mind having the even numbers reversed).
#include <stdio.h>
#include <stdlib.h>
void separate(int m, int n) {
if (m == n) printf("Odd:");
if (n == 0) { printf("\nEven:"); return; }
int i;
if (scanf("%d", &i) != 1) exit(EXIT_FAILURE);
// print odd numbers before recursing; even numbers after recursing
if (i % 2 == 1) printf(" %d", i);
separate(m, n - 1);
if (i % 2 == 0) printf(" %d", i);
if (m == n) printf("\n\n");
}
See https://ideone.com/GpE7rC which includes the calling and input
separate(3, 3); // for 3 numbers
One way would be say:
int odd1, odd2, odd3, numOdd = 0;
/* Code as above */
scanf("%d", &num);
if (num%2)
{
if (numOdd == 0)
{
odd1 = num;
numOdd++;
}
else if (numOdd == 1)
{
odd2 = num;
numOdd++;
}
/* And continue */
}
else
{
/* Repeat with even1, even2, even3 and numEven */
}
/* Print out numOdd oddn's */
/* Print out numEven evenn's */
It seems a silly exercise, but at least you'll get a lot of practise writing if statements...
I also thought:
scanf("%d", &num1);
scanf("%d", &num2);
scanf("%d", &num3);
Might be shorter, but then you don't need a for loop, unless you do something like:
printf("Odd: ");
for (i = 0; i < 3; i++)
{
int thisNum;
if (i == 0) thisNum = num1;
else if (i == 1) thisNum = num2;
/* etc */
if (thisNum % 2) printf("%d ", thisNum);
}
The problems is that you cannot use arrays. Hence you must not use strings, which are arrays. Allowing the use of scanf and printf is a deliberate trap set by your teacher - there is no way of using them in an useful way without resorting to use of arrays, explicit or implied.
Therefore you must do this:
#include <stdio.h>
#include <ctype.h>
void print_number(int n)
{
if (n < 0) {
putchar('-');
n = -n;
}
if (n == 0)
putchar('0');
if (n / 10)
print_number(n / 10);
putchar(n % 10 + '0');
}
int main(void) {
putchar('E');
putchar('n');
putchar('t');
putchar('e');
putchar('r');
putchar(' ');
putchar('t');
putchar('h');
putchar('r');
putchar('e');
putchar('e');
putchar(' ');
putchar('i');
putchar('n');
putchar('t');
putchar('e');
putchar('g');
putchar('e');
putchar('r');
putchar('s');
putchar(':');
putchar(' ');
fflush(stdout);
int odd1, odd2, odd3, odd_count = 0;
int even1, even2, even3, even_count = 0;
for(int i = 0; i < 3; i++)
{
int number = 0;
int c;
while (1) {
c = getchar();
if (isspace(c)) {
if (c == '\n')
break;
while ((c = getchar()) == ' ');
ungetc(c, stdin);
break;
}
else if (isdigit(c)) {
number = number * 10 + c - '0';
}
}
if (number % 2) {
switch (odd_count) {
case 0: odd1 = number; break;
case 1: odd2 = number; break;
case 2: odd3 = number; break;
}
odd_count ++;
}
else {
switch (even_count) {
case 0: even1 = number; break;
case 1: even2 = number; break;
case 2: even3 = number; break;
}
even_count ++;
}
}
putchar('O');
putchar('d');
putchar('d');
putchar(':');
putchar(' ');
if (odd_count >= 1) {
print_number(odd1);
}
if (odd_count >= 2) {
putchar(' ');
print_number(odd2);
}
if (odd_count >= 3) {
putchar(' ');
print_number(odd3);
}
putchar('\n');
putchar('E');
putchar('v');
putchar('e');
putchar('n');
putchar(':');
putchar(' ');
if (even_count >= 1) {
print_number(even1);
}
if (even_count >= 2) {
putchar(' ');
print_number(even2);
}
if (even_count >= 3) {
putchar(' ');
print_number(even3);
}
putchar('\n');
}
This code does not use any arrays.
If you cannot define any functions (other than main obviously), you must inline the print_number in the 6 places changing the recursion into iteration. Good luck!
If the teacher however accepts the use of strings in a task that does not allow the use of arrays, you can take it as a license to disregard all silly restrictions set by them.
Given the fact that you are learning C, perhaps your teacher wants to teach you some pointer arithmetics instead of using arrays like in this code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i = 0;
int *odd = (int*)malloc(3 * sizeof(int));
int odd_count = 0;
int *even = (int*)malloc(3 * sizeof(int));
int even_count = 0;
printf("Enter three integers: ");
for(i=0; i<3; i++)
{
int num = 0;
scanf("%d", &num);
if(!(num%2))
{
*even++ = num;
even_count++;
}
if(num%2)
{
*odd++ = num;
odd_count++;
}
}
even -= even_count;
odd -= odd_count;
printf("\nEven: ");
for(i=0; i<even_count; i++)
{
printf("%d ", *even++);
}
printf("\nOdd: ");
for(i=0; i<odd_count; i++)
{
printf("%d ", *odd++);
}
free(odd);
free(even);
return 0;
}

How do i print all the odd numbers?

I want to print all the odd numbers from 14 to 156 using an infinite loop, break and continue. But, when i run it does not display anything!!
int main()
{
int x;
int y = 14;
while(x) {
if(y % 2 == 0) {
continue;
}
else if(y % 3 == 0) {
printf("%d\n", y);
}
if(y == 156) {
break;
}
y++;
}
return 0;
}
The problem with your code is that it uses an operation with unpredictable results. Specifically, declaring int x; without initializing it, and then using it as your termination condition in while(x) is the problem. On many platforms and compilers, this will retain whatever value was already in the memory occupied by x. In that case, you may see no print statements because x starts with the value zero and the loop never runs.
You should make your loop into an infinite loop:
int main()
{
int x;
for(x = 14; ; x++) {
if(x % 2 == 0) {
continue;
}
if(x >= 156) {
break;
}
printf("%d\n", x);
}
return 0;
}
[IDEOne link]
This will print the values excluding 156 itself. To include 156, put the break condition after the printf call:
printf("%d\n", x);
if(x >= 156) {
break;
}
Alternatively you can change >= to just >.
You do not need else if you have break or continue.
If you have to use a while loop, the situation is a tad more complex because you have to increment before you continue to avoid an infinite loop:
int main() {
int x = 14;
while(1) {
if(x % 2 == 0) {
x++;
continue;
}
if(x >= 156) {
break;
}
printf("%d\n", x++);
}
return 0;
}
[IDEOne Link]
You can avoid the extra increment if you can forgo the continue:
int main() {
int x = 14;
while(1) {
if(x % 2) {
printf("%d\n", x);
}
if(x++ == 156) {
break;
}
}
return 0;
}
[IDEOne Link]
I have also removed your check for x % 3 == 0 since it is not clear what the purpose of that is within the constraints of your problem.
With an infinite loop:
#include <stdio.h>
#include <stdlib.h>
int main() {
int y=14;
while(1){
if(y & 1){
printf("%d\n",y);
}
if(y>=156){
break;
}
y++;
}
return 0;
}
Preferred method, with for loop:
#include <stdio.h>
#include <stdlib.h>
int main() {
int start=14;
start |= 1; //This will increment by one if your start value is even
for (start; start<=146; start+=2) {
printf("%d\n", start);
}
return 0;
}
An infinite loop with a break is not the right way to do this. Use a "for" loop and your code will be much clearer. Start it at 15 and increment by 2 until 156.
There are several problems in your logic.
1. Variable `x` is of no use. You can use variable `y` to terminate the loop.
2. No need to check if the number is a multiple of 3.
3. No need to check for even numbers is either.
I have modified the code and it is giving correct results but I'll urge you to read the above points and try to get the code right.
int main()
{
int y = 14;
while(y) {
if (y==156)
break;
if(y % 2 != 0) {
printf("%d ",y);
}
y++;
}
return 0;
}
A better and faster way would be to start with 15 and increment variable y's value by 2 till its <=156.
int main()
{
int y = 15;
while(y) {
if (y==157)
break;
printf("%d ",y);
y+=2;
}
return 0;
}
Your code has undefined behavior because the variable x is uninitialized and used as the condition in the while statement. You could fix this with while (1) but there would indeed be an infinite loop in your program because the test for evenness occurs before the test for termination on 156.
The problem is solved simply with a standard for loop:
#include <stdio.h>
int main(void) {
for (int y = 14; y < 156; y++) {
if (y % 2 != 0) {
printf("%d\n", y);
}
}
return 0;
}
Which can be simplified as this, only enumerating odd numbers:
#include <stdio.h>
int main(void) {
for (int y = 15; y < 156; y += 2) {
printf("%d\n", y);
}
return 0;
}
If you are required to use break, continue and a infinite loop, you can indeed use the classic forever C loop, a for loop without a termination condition:
#include <stdio.h>
int main(void) {
for (int y = 14;; y++) {
if (y == 156)
break;
if (y % 2 == 0)
continue;
printf("%d\n", y);
}
return 0;
}
Well ...
#include <stdio.h>
#include <stdint.h>
#include <errno.h>
/* Prints even or add numbers between to and from.
Works for negative numbers.
Works up and down.
*/
int print_even_or_odd(long long from, long long to, int even)
{
if (((INT32_MAX < from) || (INT32_MIN > from)) ||
((INT32_MAX < to) || (INT32_MIN > to)))
{
fprintf(stderr, "Invalid input.\n");
errno = EINVAL;
return -1;
}
printf("from=%d to %d\n", (int) from, (int) to);
int sign = (to < from) ?-1 :1;
/* Adjust "from" to next even/odd number. */
if ((!even && !(from & 1)) || (even && (from & 1)))
{
from += sign;
}
/* Adjust "to" to the previous even/odd number. */
if ((!even && !(to & 1)) || (even && (to & 1)))
{
to -= sign;
}
{
size_t steps = (size_t) (sign * ((to - from) / 2)) + 1;
if (0 == steps)
{
printf("Nothing to do.\n");
return 0;
}
while (1)
{
if (0 >= steps)
{
break;
}
--steps;
printf("%d\n", (int) (to - sign * 2 * (int) steps));
continue; /* as having continue is a requirement ... ;-) */
}
}
return 0;
}
int main(void)
{
print_even(14, 156, 0);
print_even(156, 14, 0);
print_even(-14, -156, 0);
print_even(-156, -14, 0);
}

Need 10 outputs per line

I am having trouble refining some code. My code takes a number "n" and calculates that many prime numbers. I need to display 10 primes per line of output data. Any tips would be appreciated.
#include <stdio.h>
int main()
{
int n, i = 3, count, c;
printf("How many primes would you like?");
scanf("%d",&n);
if ( n >= 1 )
{
printf("2");
}
for ( count = 2 ; count <= n ; )
{
for ( c = 2 ; c <= i - 1 ; c++ )
{
if ( i%c == 0 )
break;
}
if ( c == i )
{
printf(" %d",i);
count++;
}
i++;
}
return 0;
}
Just try
printf(" %5d", i);
/* ^ to help align the numbers
and
if ((count + 1) % 10 == 0)
fputc(stdout, '\n');
fix for the first time when you already print 2.
bool is_prime(int anyNum) //takes an integer array returns, is_prime
{
bool is_prime = true;
for (int c = 2; c <= anyNum - 1; c++)
{
if (anyNum % c == 0)
{
//printf("%d is not prime\r\n" , anyNum);
is_prime = false;
}
}
return is_prime;
}
int main()
{
int num_primes;
printf("How many primes would you like: ");
std::cin >> num_primes;
printf("\r\nScanned Primes Are---\r\n");
int foundPrimes = 0;
int x = 0;
for (; x <= num_primes; x++)
{
bool gotLuckyFindingPrime = is_prime( x );
if (gotLuckyFindingPrime)
{
if (foundPrimes % 10 == 0)
{
printf("\r\n");
}
printf(" %d", x);
foundPrimes = (foundPrimes + 1) % 10;
}
}
}
Does handle ten digit showing on cmd too, you can experiment with formatting

Unusual Floating point exception (core dumped) Error with C

I am currently a student, trying to get factorials to print out as prime numbers multiplied to certain exponents like so:
5! = (2^3)(3^1)(5^1)
However, I keep getting an unusual error, which occurs right after using scanf to retrieve my input (By the way, I would really appreciate someone showing me how to retrieve multiple inputs from an exterior file to do this using input redirection, since that's how we were supposed to retrieve our inputs for this).
Anyway, I'm assuming this error is somewhere in the specification for my while loop. I would greatly appreciate any help/tips/pointers. Thank you!
#include <stdio.h> //headers
#include <stdbool.h>
//function prototypes - I will be using functions inside of each other
int find_prime_count (int prime, int num);
int find_next_prime (int prime);
bool is_prime (int num);
int main(void) //main function
{
int primeCount[100] = {0}, prime = 2, fact, i = 2, temp = 2, currentPrimeCount, printCount = 0;
printf ("Enter number: ");
scanf ("%d", &fact);
while (i <= fact)
{
printf ("i is less than factorial");
while (temp != 1)
{
printf ("Temp is not equal to one");
currentPrimeCount = find_prime_count (prime, temp);
printf ("currentPrimeCount calculated");
temp = temp / (currentPrimeCount * prime);
printf ("Temp updated");
primeCount[prime + 1] += currentPrimeCount;
printf ("primeCount[prime + 1] updated");
prime = find_next_prime (prime);
printf ("Next prime found");
}
i += 1;
temp = i;
}
printf ("%3d! = ", fact);
i = 0;
while (i < 100)
{
if (primeCount[i] != 0)
{
if (printCount == 0)
{
printf ("(%d^%d)", i, primeCount[i]);
}
else if (printCount != 0)
{
printf (" * (%d^%d)", i, primeCount[i]);
}
printCount += 1;
if ((printCount % 9) == 0)
{
printf ("/n");
}
if ((printCount > 9) && ((printCount % 9) == 0))
{
printf (" ");
}
}
}
return 0;
}
bool is_prime (int num)
{
bool check = true; //sets check variable to true
int i = 2; //starts counter variable at 2 (will test all numbers >=2 && <num)
while (i < num && check == true)
{
if ((num % i) == 0) //if it is divisible by any number other than 1 and itself
{
check = false; //it is not a prime number and the check becomes false
}
i += 1; //increasing counter
}
return check; //returns boolean value
}
int find_next_prime (int prime)
{
int i = prime;
bool check = false;
printf ("find_next_prime starts.");
while (check == false)
{
i += 1;
check = is_prime (i);
}
printf ("find_next_prime ends.");
return i;
}
int find_prime_count (int prime, int num)
{
int count = 0;
printf ("find_prime_count starts.");
while ((prime % num) == 0)
{
count += 1;
num = num / prime;
}
printf ("find_prime_count ends.");
return count;
}
Using gdb, I can tell that it is a divide by zero error in prim % num.
Hints:
Compile with the -g flag
Run using gdb
Set a breakpoint ...

Resources