finding prime numbers between a range in C - c

I am trying to find the prime numbers in a range using C language. My code does not give an output and I think there is a logical error here which I cannot figure out. Can anyone please help?
#include <stdio.h>
int main() {
int lowerLevel;
int upperLevel;
int i; //counter variable
int prime = 0;
int flag = 0;
printf("Enter the lower limit and upper limit of the range followed by a comma :");
scanf("%d %d", &lowerLevel, &upperLevel);
for (i = 2; i <= upperLevel; ++i) {
if (i % 2 == 0) {
flag = 1;
break;
}
}
if (flag == 0) {
printf("%d", i);
++i;
}
return 0;
}

Your code does not check for prime numbers, it merely checks that there is at least one even number between 2 and upperlevel, which is true as soon as upperlevel >= 2. If there is such an even number, nothing is printed.
You should instead run a loop from lowerlevel to upperlevel and check if each number is a prime and if so, print it.
Here is a modified version:
#include <stdio.h>
int main() {
int lowerLevel, upperLevel;
printf("Enter the lower limit and upper limit of the range: ");
if (scanf("%d %d", &lowerLevel, &upperLevel) != 2) {
return 1;
}
for (int i = lowerLevel; i <= upperLevel; ++i) {
int isprime = 1;
for (int p = 2; p <= i / p; p += (p & 1) + 1) {
if (i % p == 0) {
isprime = 0;
break;
}
}
if (isprime) {
printf("%d ", i);
}
}
printf("\n");
return 0;
}
This method is simplistic but achieves the goal. More efficient programs would use a sieve to find all prime numbers in the range without costly divisions.

Optimal method with Sieves of Eratosthenes
You should use the sieves of Eratostenes algorithm, it is way more efficient to get the different prime number.
it does so by iteratively marking as composite (i.e., not prime) the multiples of each prime, starting with the first prime number, 2
Basically you consider all numbers prime by default, and then you will set as false the prime number, see below code:
#include <stdio.h>
/// unsigned char saves space compared to integer
#define bool unsigned char
#define true 1
#define false 0
// https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
void printPrimesRange(int lowerLevel, int n) {
if (lowerLevel < 0 || n < lowerLevel) // handle misused of function
return ;
bool isPrime[n + 1];
memset(isPrime, true, n + 1);
int cnt = 0; // NB: I use the counter only for the commas and final .\n, its optional.
if (lowerLevel <= 2 && n >= 2) { // only one even number can be prime: 2
++cnt;
printf("2");
}
for (int i = 3; i <= n ; i+=2) { // after what only odd numbers can be prime numbers
if (isPrime[i]) {
if (i >= lowerLevel) {
if (cnt++)
printf(", ");
printf("%d", i); // NB: it is better to print all at once if you can improve it
}
for (int j = i * 3; j <= n; j+=i*2) // Eratosthenes' Algo, sieve all multiples of current prime, skipping even numbers
isPrime[j] = false;
}
}
printf(".\n");
}
int main(void) {
int lowerLevel;
int upperLevel;
printf("Enter the lower limit and upper limit of the range with a space in-between:"); // space, not comma
scanf("%d %d", &lowerLevel, &upperLevel);
printPrimesRange(lowerLevel, upperLevel);
return 0;
}

Let's follow the logic of your code:
#include <stdio.h>
#include <string.h>
int main() {
int lowerLevel;
int upperLevel;
int i; //counter variable
int prime = 0;
int flag = 0;
printf("Enter the lower limit and upper limit of the range followed by a comma :");
scanf("%d %d", &lowerLevel, &upperLevel);
for (i = 2; i <= upperLevel; ++i) {
if (i % 2 == 0) {
flag = 1;
break;
}
}
if (flag == 0) {
printf("%d", i);
++i;
}
return 0;
}
First of all, you have a loop:
for (i = 2; i <= upperLevel; ++i) {
if (i % 2 == 0) {
flag = 1;
break;
}
}
this loop tries to find a number i that is a multple of 2, because as soon you get one, you jump out of the loop. So your loop can be expressed better as:
for (i = 2; i <= upperLevel && i % 2 != 0; ++i) {
}
/* i > upperLevel || i % 2 == 0 */
if (i <= upperLevel && i % 2 == 0) {
flag = 1;
}
We still need to check if i <= upperLevel && i % 2 == 0 to set the variable flag = 1 if we exited the loop because i was a multiple of 2, but the break; is not necessary because we are already out of the loop.
Now let's check that the first value we initialize i is, indeed 2 (which is a multiple of 2) and the consecuence of this is that the loop is never going to be entered. Se we can eliminate it completely, giving to:
i = 2;
if (i <= upperLevel && i % 2 == 0) {
flag = 1;
}
now, the second clause of the if test is always true, so we can take it off, giving:
i = 2;
if (i <= upperLevel) {
flag = 1;
}
Now, let's append the second part:
i = 2;
if (i <= upperLevel) {
flag = 1;
}
if (flag == 0) {
printf("%d", i);
++i;
}
return 0;
so, the first thing we see here is that your ++i; statement is nonsense, as it is the last statement to be
executed before exiting the program, so we can also take it off.
i = 2;
if (i <= upperLevel) {
flag = 1;
}
if (flag == 0) {
printf("%d", i);
}
return 0;
Now we see that you print the value of i only if the value of flag is zero, but flag only conserves its zero value if the value of i > upperLevel, and as i is fixed, the printing of i only occurs if you input a value of upperlevel that is less than 2.
We can rewrite the above code as this:
if (2 > upperLevel) {
printf("%d", 2);
}
Your program will print 2 only if you provide a value of upperLevel less than 2.

Related

In C, can i use scanf with just one %d input but get 2 variables with that same input?

By the time i finish counting the digits(K) with a while/do loop, the original N number is lost and its now 0. So i cant rly go to step 4). Thats why i thought id create 2 variables with the same input so i can just do the 4) step as a seperate process entirely.
(CONTEXT
basically the task is to make a program that 1) read a number N (1<=N<=999999999) with scanf,
2) if the number is out of mentioned bounds, make message "Wrong Input" appear,
3) make it count the digits of said number, (digits as K),
4) If N includes K as a digit, make message "Yes" appear, otherwise make "No" appear.)
int main()
{
int K,N;
scanf("%d", &N);
if (N<=1 || N>=999999999)
{
printf("Wrong Input\n");
}
else
{
do
{
N=N/10;
K++;
}
while(N!=0);
}
return 0;
}
else
{
int M = N;
do
{
M=M/10;
K++;
}
while(M!=0);
}
You can just create a new local variable and store the value of N to be used later
#include <stdio.h>
int main() {
// initializing with 0 because 0 = false and 1 = true, to use true or false you need the bool.h header file
int containsDigit = 0;
int K, N, digits = 0;
scanf("%d", &N);
K = N;
if (N <= 1 || N >= 999999999) {
printf("Wrong Input\n");
} else {
while (N != 0) {
N /= 10;
digits++;
}
while(K != 0) {
int cdigit = K % 10;
if (cdigit == digits) {
containsDigit = 1;
break;
}
K /= 10;
}
if (containsDigit) printf("yes");
else printf("No");
}
return 0;
}

How to express integer as a product of its prime factors?

//Determine the prime factors of a number
for(i = 2; i <= num; i++) { //Loop to check the factors.
while(num % i == 0) { //While the input is divisible to "i" which is initially 2.
printf("%d ", i); //Print the factor.
num = num / i; //Divide the num by "i" which is initially 2 to change the value of num.
}
}
I know that this is the way of finding the prime factors of a number using for loop. But I don't know how to express the output integer as a product of its prime factors.
For example, INPUT IS: 10 ||
OUTPUT IS: 2 x 5 = 10. How do we do this? TIA.
You should:
Save the original value.
Print the operator x between each prime factors.
Print the original value at the end.
#include <stdio.h>
int main(void) {
int num;
int i;
int start_num;
int is_first = 1;
if(scanf("%d", &num) != 1) return 1;
start_num = num; //Save the original value.
//Determine the prime factors of a number
for(i = 2; i <= num; i++) { //Loop to check the factors.
while(num % i == 0) { //While the input is divisible to "i" which is initially 2.
if(!is_first) printf("x "); //Print the operator before second and later operands.
printf("%d ", i); //Print the factor.
num = num / i; //Divide the num by "i" which is initially 2 to change the value of num.
is_first = 0; //Mark that there is already one or more operand.
}
}
printf("= %d\n", start_num); //Print the original value.
return 0;
}
You can output the factors with the appropriate punctuation:
// Output the prime factors of a number
void factorize(int num) {
int n = num; // save the initial value of num
const char *sep = ""; // initial separator is an empty string
for (int i = 2; i <= num / i; i++) { // stop when num is reduced to a prime
while (num % i == 0) { // while the input is divisible to "i"
num = num / i; // divide the num by "i" (remove the factor)
printf("%s%d", sep, i); // print the separator and the factor.
sep = " x "; // change the separator for any further factors
}
}
if (num > 1 || n <= 1) {
printf("%s%d", sep, num); // print the last or single factor.
}
printf(" = %d\n", n); // print the rest of the equation
}
I've revised the code to give something that's a bit more robust than what I posted previously, as well as being slightly more efficient. Again I assume you want (unsigned) 32-bit input via stdin in the range: [1, 2^32 - 1]
As far as the algorithm is concerned, it should be apparent that searching for factors need only test candidates up to floor(sqrt(num)). There are also factors with multiplicity, e.g., (24) => {2, 2, 2, 3}.
Furthermore, after factoring out (2), only odd factors need to be tested.
For a 32-bit (unsigned) type, there will be fewer than (32) prime factors. This gives a simple upper-bound for a fixed-size array for storing the successive prime factors. The prime factors in the array are in ascending order, by virtue of the algorithm used.
/******************************************************************************/
#include <stdio.h>
int main (void)
{
/* print a value in [1, 2^32 - 1] as a product of primes: */
unsigned long int n, u, prime[32];
int np = 0;
if (scanf("%lu", & n) != 1 ||
((n == 0) || ((n & 0xffffffffUL) != n)))
{
fprintf(stderr, "factor < u32 = 1 .. 2^32 - 1 >\n");
return (1);
}
if (n == 1) /* trivial case: */
{
fprintf(stdout, "1 = 1\n");
return (0);
}
u = n; /* (u) = working value for (n) */
for (; (u & 0x1) == 0; u >>= 1) /* while (u) even: */
prime[np++] = (2);
while (u > 1)
{
unsigned long q, d = 3, c = 0; /* (c)omposite */
if (np != 0) /* start at previous odd (prime) factor: */
d = (prime[np - 1] == 2) ? (3) : prime[np - 1];
for (; (c == 0) && (q = u / d) >= d; )
{
if ((c = (q * d == u)) == 0) /* not a factor: */
d += 2;
}
prime[np++] = (d = (c == 0) ? u : d);
u /= d; /* if (u) is prime, ((u /= d) == 1) (done) */
}
for (int i = 0; i < np; i++)
{
const char *fmt = (i < np - 1) ? ("%lu x ") : ("%lu = ");
fprintf(stdout, fmt, prime[i]);
}
fprintf(stdout, "%lu\n", n);
return (0);
}
/******************************************************************************/

Sum of digits not including the same digit twice

(Purpose of the code is write in the title) my code work only if i put the same number once and in the end like - 123455 but if i write 12345566 is dosent work or 11234 it dosent wort to someone know why? i have been trying for a few days and i faild agine and agine.
while(num)
{
dig = num % 10 // dig is the digit in the number
num /= 10 // num is the number the user enter
while(num2) // num2 = num
{
num2 /= 10
dig2 = num2 % 10 // dig2 is is the one digit next to dig
num2 /= 10
if(dig2 == dig) // here I check if I got the same digit twice to
// not include him
{
dig2 = 0
dig = 0
}
}
sum = sum + dig + hold
}
printf("%d", sum)
Well your code's almost correct but there's are somethings wrong ,
When you declared num2 to be equal to num1 it was out of the loop so as soon as one full loop execution is done , num2 still remains to be less than zero or to be zero if it was a unsigned int, so according to the condition the second loop wont execute after its first run.
So mind adding ,
num2 = num1
inside your first loop .
Also your updating num2 twice which i think you wont need to do after the first change .
Full code which i tried
#include<stdio.h>
int main(void)
{
int num;
int num2;
int sum = 0;
int dig, dig2;
scanf_s("%d", &num);
while (num>0)
{
dig = num % 10; //dig is the digit in the number
num /= 10;
num2 = num;// num is the number the user enter
while (num2>0) // num2 = num
{
dig2 = num2 % 10; // dig2 is is the one digit next to dig
if(dig2 == dig) // here i check if i got the same digit twice to //not include him
{
dig = 0;
}
num2 /= 10;
}
sum = sum + dig ;
}
printf("%d", sum);
return 0;
}
O(n)
#include <stdio.h>
int main () {
unsigned int input = 0;
printf("Enter data : ");
scanf("%u", &input);
int sum = 0;
int dig = 0;
int check[10] = {0};
printf("Data input: %u\n", input);
while(input) {
dig = 0;
dig = input%10;
input = input/10;
if (check[dig] == 0) {
check[dig]++;
sum += dig;
}
}
printf("Sum of digits : %d\n", sum);
return 0;
}
My program uses a character array (string) for storing an integer. We convert its every character into an integer and I remove all integers repeated and I calculate the sume of integers without repetition
My code :
#include <stdio.h>
#include <stdlib.h>
int remove_occurences(int size,int arr[size])
{int s=0;
for (int i = 0; i < size; i++)
{
for(int p=i+1;p<size;p++)
{
if (arr[i]==arr[p])
{
for (int j = i+1; j < size ;j++)
{
arr[j-1] = arr[j];
}
size--;
p--;
}
}
}
for(int i=0;i<size;i++)
{
s=s+arr[i];
}
return s;
}
int main()
{
int i=0, sum=0,p=0;
char n[1000];
printf("Input an integer\n");
scanf("%s", n);
int T[strlen(n)];
while (n[i] != '\0')
{
T[p]=n[i] - '0'; // Converting character to integer and make it into the array
p++;i++;
}
printf("\nThe sum of digits of this number :%d\n",remove_occurences(strlen(n),T));
return 0;
}
Example :
Input : 1111111111 Output : 1
Input : 12345566 Output : 21
Or ,you can use this solution :
#include <stdio.h>
#include <stdbool.h>
bool Exist(int *,int,int);
int main ()
{
unsigned int n = 0;
int m=0,s=0;
printf("Add a number please :");
scanf("%u", &n);
int T[(int)floor(log10(abs(n)))+1];
// to calculate the number of digits use : (int)floor(log10(abs(n)))+1
printf("\nThe length of this number is : %d\n",(int)floor(log10(abs(n)))+1);
int p=0;
while(n!=0)
{
m=n%10;
if(Exist(T,p,m)==true)
{
T[p]=m;
p++;
}
n=n/10;
}
for(int i=0;i<p;i++)
{
s=s+T[i];
}
printf("\nSum of digits : %d\n", s);
return 0;
}
bool Exist(int *T,int k,int c)
{
for(int i=0;i<k;i++)
{
if(T[i]==c)
{
return false;
}
}
return true;
}

Coding for multiple modes in C?

My assignment is to find all possible modes for a set of numbers (0 to 100).
We were told to do so using arrays and also to count the frequency that each number occurs.
I've coded for the mode, however, my program does not work is there are multiple modes (example: 1, 2, 7, 7, 9, 10, 7, 2, 2. In this stance, 2 and 7 are both the mode and my program needs to print both of them, but mine doesn't).
I think I might have to make another array set, but I'm not sure? Any advice would be appreciated.
Here is what I have:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main() {
int x, i, c[101], mode;
printf("please enter test scores between 0 and 100\n");
i = 0;
mode = 0;
while (i <= 100) { //setting all values to 0
c[i] = 0;
i = i + 1;
}
scanf("%d", &x); // scanning in the test scores
while ((x >= 0) && (x <= 100)) { // counting how often each score appears
c[x] = c[x] + 1;
if (c[x] >= mode) {
mode = x;
}
scanf("%d", &x);
}
printf("THE MODE(S) ARE %d\n", mode);
i = 0;
while (i <= 100) { //printing all values so long as they've occurred at least once
if (c[i] > 0) {
printf("%d occurs %d times\n", i, c[i]);
}
i = i + 1;
}
}
You have to count the highest frequency of any number and if that frequency equals the frequency of any other number then that number will also be mode.
So the changes that you need to do are:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main ()
{
int x, i, c[101], mode;
printf("please enter test scores between 0 and 100\n");
i = 0;
mode = 0;
while (i <= 100) //setting all values to 0
{
c[i] = 0;
++i;
}
scanf("%d", &x); // scanning in the test scores
while ((x >= 0) && (x <= 100)) // counting how often each score appears
{
c[x] = c[x] + 1;
if (c[x] >= mode)
{mode = c[x];}
scanf("%d", &x);
}
for(i=0;i<=100;i++){//printing all values having highest frequency
if (c[i]==mode)
{
printf("THE MODE(S) ARE %d\n", i);
}
i = 0;
while (i<=100) //printing all values so long as they've occurred at least once
{
if (c[i] > 0)
{
printf("%d occurs %d times\n", i, c[i]);
}
++i;
}
}
Instead of determining the mode in the main entry loop, you should determine the maximum count. Then you can print all values with this count of occurrences in a final loop.
You should also check the return values of scanf().
I would also advise to use an initializer for the array to avoid a loop and to use for loops that more clearly identify the initialization, test and increment of the loop index.
Here is a corrected version of your code:
#include <stdio.h>
int main() {
int x, i, c[101] = { 0 }, max_repeat;
printf("please enter test scores between 0 and 100\n");
max_repeat = 0;
// read the test scores and compute the maximum repeat count
while (scanf("%d", &x) == 1 && x >= 0 && x <= 100) {
c[x] += 1;
if (max_repeat < c[x]) {
max_repeat = c[x];
}
}
printf("The mode(s) are");
for (i = 0; i <= 100; i++) {
if (c[i] == max_repeat) {
printf(" %d", i);
}
}
printf("\n");
return 0;
}

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