How to find the nth prime in C - c

This application will receive a number n. After receiving this number, the program has to show the n-th prime in the list of primes. For example, if the user enters 3, the program is supposed to display 5, because 5 is the third prime starting at 2. I know that something is wrong with my code but I don't know where the problem is and how I can fix it.
#include <stdio.h>
int main() {
int n, i, flag, prime;
int counter = 1;
scanf("%d", &n);
if (n == 1) prime = 2;
else
do{
prime = 3;
for (i = 2; i < prime; i++) {
flag = 1;
if (prime % i == 0) {
flag = 0;
}
}
if (flag == 1)
counter++;
prime++;
} while (counter != n);
if (counter == n)
printf("%d\n", prime);
return 0;
}

Fix sample of remains of your policy like this :
#include<stdio.h>
int main(void){
int n, i, flag, prime;
int counter = 1;
scanf("%d", &n);
if (n == 1)
prime = 2;
else {
prime = 1;
do{
prime += 2;
flag = 1;
for (i = 3; i < prime; i+=2){
if (prime % i == 0) {
flag = 0;
break;
}
}
if(flag == 1)
counter++;
} while (counter != n);
}
printf("%d\n", prime);
return 0;
}

You are resetting flag to 1 every time through the loop, so 'flag' will only tell you if prime is divisible by "prime-1", which of course it never is.

Related

Sum of prime factors

I am trying to show the sum of the prime factors of a given number and
I'm having difficulties displaying the prime factors in my output.
Sample Output:
Input number: 6
Factors are: 1 2 3
Sum of its factor: 1 +2 +3 =6
I am able to show the sum but I want to show the 1+2+3=6 like in the sample above where the factors are 1 2 3.
Can you help me correct my syntax to achieve this? Thanks in advance.
Here's my code:
#include <stdio.h>
int main() {
int i, j, num, isPrime, sum;
printf("Input number: ");
scanf("%d", &num);
printf("Factors are: ", num);
for (i = 1; i <= num; i++) {
if (num % i == 0) {
isPrime = 1;
for (j = 2; j <= i / 2; j++) {
if (i % j == 0) {
isPrime = 0;
break;
}
}
if (isPrime == 1) {
printf("%d ", i);
sum += i;
}
}
}
printf("\nSum of its factor : %d", sum);
return 0;
}
Your code actually has undefined behavior because sum is not initialized to 0. It produces the correct sum only by chance.
You can store the factors in an array, or even construct the expression as you go with sprintf. The maximum length of the expression is not very large as there can be at most 9 different prime factors (29!! > 232)
Here is a modified version:
#include <stdio.h>
int main() {
char expr[9 * 11 + 1];
int i, j, pos, num, isPrime, sum;
printf("Input number: ");
if (scanf("%d", &num) != 1)
return 1;
printf("Factors are: 1"); // always include 1
pos = 0;
expr[pos] = '\0';
sum = 1;
for (i = 2; i <= num; i++) {
if (num % i == 0) {
isPrime = 1;
for (j = 2; j * j <= i; j++) {
if (i % j == 0) {
isPrime = 0;
break;
}
}
if (isPrime == 1) {
pos += sprintf(expr + pos, "+%d", i);
printf(" %d", i);
sum += i;
}
}
}
printf("\nSum of its factors: 1%s = %d\n", expr, sum);
return 0;
}
Output:
Input number: 6
Factors are: 1 2 3
Sum of its factors: 1+2+3 = 6
Here is a more robust and much faster version that does not have undefined behavior for very large values of num:
#include <stdio.h>
int main() {
char expr[9 * 11 + 1];
int i, pos, num;
unsigned sum;
printf("Input number: ");
if (scanf("%i", &num) != 1)
return 1;
printf("Factors are: 1"); // always include 1
pos = 0;
expr[pos] = '\0';
sum = 1;
for (i = 2; num / i >= i; i++) {
if (num % i == 0) {
pos += sprintf(expr + pos, "+%d", i);
printf(" %d", i);
sum += i;
do { num /= i; } while (num % i == 0);
}
}
if (num != 1) {
pos += sprintf(expr + pos, "+%d", num);
printf(" %d", num);
sum += num;
}
printf("\nSum of its factors: 1%s = %u\n", expr, sum);
return 0;
}
Test:
Input number: 0x7fffffff
Factors are: 1 2147483647
Sum of its factors: 1+2147483647 = 2147483648
Since you want to print all the prime factors twice, you should do that in a way so that you can avoid duplicated code. Here is an idea:
#include <stdio.h>
/* Return the smallest prime that is smaller than or equal to n */
/* Assumes that the argument is greater than 1 */
int getFirst(int n)
{
int i;
for(i = 2; i <= n; i++)
if(n % i == 0)
return i;
}
int main()
{
int num, x, tmp, sum=0;
scanf("%d", &num);
tmp = num;
printf("Factors are: ");
while(1) {
x = getFirst(tmp);
printf("%d ", x);
if (x == tmp) /* If we are at the last prime */
break;
tmp /= x;
}
printf("\n");
printf("Sum of factors is: ");
tmp = num;
while(1) {
x = getFirst(tmp);
printf("%d ", x);
sum += x;
if(x == tmp) /* If we are at the last prime */
break;
printf("+ ");
tmp /= x;
}
printf("= %d\n", sum);
}
But as has been pointed out in the comments. 1 is not a prime, and that's why I excluded it.

Sum of the odd digits and even digits from the input and compare them. If both are equal print stat1 else stat2

This is the code, this code is not working. For loop needs to be used for this program. I need help to make this work.
Program prints same statement for different numbers. Kindly debug this and help me to understand the concept.
#include<stdio.h>
int main()
{
int n,i,sum=0,sum1=0,rem;
printf("enter values\n");
scanf("%d",&n);
for(i=n;i<=n;)
{
rem=n%10;
if(rem%2 == 0)
{
sum=sum+rem;
}
else
{
sum1=sum1+rem;
}
n=n/10;
}
if(sum==sum1)
printf("I will win the Card Game");
else
printf("I will not win the Card Game");
return 0;
}
#include<stdio.h>
int main()
{
int n,i,sum=0,sum1=0,rem;
printf("enter values\n");
scanf("%d",&n);
for(i = 0; i < n;)
{
rem=n%10;
if(rem%2 == 0)
{
sum=sum+rem;
}
else
{
sum1=sum1+rem;
}
n=n/10;
}
if(sum==sum1)
printf("I will win the Card Game\n");
else
printf("I will not win the Card Game\n");
return 0;
}
Try this:
Use Array to get multiple values and compare them like below.
#include<stdio.h>
int main()
{
int n,*arr,i,sum=0,sum1=0;
printf("how many numbers\n");
scanf("%d",&n);
printf("enter values");
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
for(i=0;i<n;i++)
{
if(arr[i]%2 == 0)
sum=sum+1;
else
sum1=sum1+1;
}
if(sum==sum1)
printf("I will win the Card Game");
else
printf("I will not win the Card Game");
return 0;
}
Calculate the length of user's number, and you will know how much numbers you got with this loop:
temp = n;
length = 0;
while (temp > 0) {
length++;
temp /= 10;
}
Then insert this code before your main loop, and in your main 'for' loop head you can use full 'for' syntax:
for(i = 0; i < length; i++)
Put all together:
int main()
{
int n, i, sum = 0, sum1 = 0, rem, length, temp;
printf("enter values\n");
scanf("%d",&n);
temp = n; // Temp variable to calculate digits' count
length = 0; // Digits' counter
while (temp > 0) { // Loop to calculate digits' count
length++; // increase counter
temp /= 10; // remove the unity digit, untill the number equal to 0.
}
for(i = 0; i < length; i++) // go through all digits
{
rem = n % 10;
if(rem % 2 == 0)
{
sum = sum + rem;
}
else
{
sum1 = sum1 + rem;
}
n = n / 10;
}
if(sum == sum1)
printf("I will win the Card Game, sum: %d", sum);
else
printf("I will not win the Card Game, sum: %d, sum1: %d", sum, sum1);
return 0;
}

C Programming: How to add up divisors of an integer n

I was wondering, how can I add up the divisors displayed once I run my code?
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i;
scanf("%d", &n);
for(i = 1; i < n; i++)
{
if(n % i == 0)
{
printf("%d\n", i);
}
}
return 0;
}
If I were to enter, say, 25, it would print out 1, 5. I was wondering how to add up the two numbers 1 and 5?
Could it be as simple as this? You will want to use a simple increment operator (+=), to increment the variable sum.
int main(void)
{
int n, i, sum = 0;
if( scanf("%d", &n)!= 1){
fprintf(stderr,"Error in input\n");
exit(EXIT_FAILURE);
}
for(i = 1; i < n; i++)
{
if(n % i == 0)
{
printf("%d\n", i);
sum += i;
}
}
printf("Sum of divisors: %d\n", sum);
return 0;
}
How to add up divisors of an integer n?
Iterating n times as with for(i = 1; i < n; i++) can take a long time when n is some high value, especially if code used 64-bit integers. Instead only iterate sqrt(n) times - much faster
int factor_count(int number) {
if (number <= 1) {
return TBD_Code(number); // OP needs to define functionality for these cases.
}
int sum = 1;
int quotient;
int divisor = 1;
do {
divisor++;
quotient = number/divisor;
int remainder = number%divisor;
if (remainder == 0) {
sum += divisor;
if (quotient > divisor) sum += quotient;
}
} while (divisor < quotient);
return sum;
}
Additional improvements noted here.

Printing prime numbers up to n

I have written some code to ask the user for n, then print the prime numbers up to n. However when I use it, i.e with 10, it only prints the non-prime numbers
/* Asks for the amount of prime numbers you would like to print, then prints them */
#include <stdio.h>
int main(void)
{
int n, i, j, check;
printf("How many prime numbers would you like to print? ");
scanf("%d", &n);
for (i = 2; i <= n; i++) {
check = 0;
for (j = 2; j < i ; j++) {
if (i % j == 0) {
check = 1;
if (check == 1) {
printf("%d\n", i);
}
}
}
}
return 0;
}
How many prime numbers would you like to print? 10
4
6
6
8
8
9
10
10
I've tried everything but I think I am missing something really trivial!
This is how it should be:
for (i = 2; i <= n; i++)
{
check = 0;
for (j = 2; j < i ; j++)
{
if (i % j == 0)
{
check = 1;
break;
}
}
if (check == 0)
{
printf("%d\n", i);
}
}
Also, in the inner loop you don't have to divide the number till j < i. You don't have to go beyond i/2.
As Weather Vane said, the mod operator % returns 0 if i is exactly divisible by j and if this is true then the number is not prime. Your conditional statement is backwards.
#include <stdio.h>
int main(void)
{
int n, i, j, check;
printf("How many prime numbers would you like to print? ");
scanf("%d", &n);
for (i = 2; i <= n; i++)
{
check = 0;
for (j = 2; j < i ; j++)
{
if (i % j == 0)
{
check = 1;
break;
}
}
if (check == 0)
{
printf("%d\n", i);
}
}
return 0;
}
How many prime numbers would you like to print? 10
2
3
5
7
Several problems.
First, when you set check = 1, that means that i divides evenly, so n is not prime, so you shouldn't print it. You should be printing the number when check == 0.
Second, you're printing each time through the inner loop. You should test check at the end of the loop, to ensure that none of the numbers divided it.
As an improvement, there's no need to keep checking once you find one number that divides evenly. So you can break out of the inner loop as soon as you set check = 1.
#include <stdio.h>
int main(void)
{
int n, i, j, check;
printf("How many prime numbers would you like to print? ");
scanf("%d", &n);
for (i = 2; i <= n; i++) {
check = 0;
for (j = 2; j < i ; j++) {
if (i % j == 0) {
check = 1;
break;
}
}
if (check == 0) {
printf("%d\n", i);
}
}
return 0;
}
try looking at this code
#include <stdio.h>
int IsPrime(int num)
{
int i = 2;
for (i = 2; i < num; i++) if (num % i == 0) return 0;
return 1;
}
int main(void)
{
int n, i;
char *nStr = (char*)malloc(10);
printf("How many prime numbers would you like to print? ");
fgets(nStr, 9, stdin);
n = atoi(nStr);
for (i = 1; i <= n; i++) if (IsPrime(i)) printf("%d\n", i);
getchar();
return 0;
}
and about your code, you should print the number only if check remains 0.

C - Next 10 prime numbers

I'm having some problems with a program I'm writing here.
It's supposed to print the next 10 prime numbers of given a value -- of course, it's not working. My logic is at fault here.
For example, if the program reads the number:
2
it's supposed to print:
3, 5, 7, 11, 13, 17, 19, 23, 29, 31
Code:
#include <stdio.h>
int main() {
int n, i, count, primenumber = 1; // primenumber is a flag
printf("Insert a number:\n");
scanf("%d", &n);
for (count = 0, n++; count < 10; n++, count++ ) {
for (i = 2; i < n; i++) {
if (n % i == 0) {
primenumber = 0;
break;
}
}
if (primenumber)
printf("%d\n", n);
}
return 0;
}
I'd be very grateful if someone were to solve this problem.
Thanks.
==UPDATE==
I did it!
The crucial change was with the primenumber flag. I inserted it inside the while, always set to 1. If set outside the while, the flag never resets and further tests won't occur -- depending on the number you give when prompted.
Here's the updated, functional code:
#include <stdio.h>
int main() {
int n, i, count = 0, primenumber;
printf("Insert a number: ");
scanf("%d", &n);
n++; // we do not want to print the prompted number
while (count < 10) {
primenumber = 1; // primenumber is set as flag
for (i = 2; i < n / 2; i++) {
if (n % i == 0) {
primenumber = 0;
break;
}
}
if (primenumber) {
printf("%d\n", n);
count++; // increment count only when prime
}
n++;
}
return 0;
}
I decided not to delete this post. I'm sure someone, someday, will find it useful.
Split your code a little arrange a bit more and present it
int isPrime ( int n )
{
if (n <= 1) return 0; // zero and one are not prime
unsigned int i;
for (i=2; i*i<=n; i++) {
if (n % i == 0) return 0;
}
return 1;
}
int main() {
int n, count; // primenumber is a flag
printf("Insert a number:\n");
scanf("%d", &n);
count = 0 ;
n++ ;
for ( ; count < 10; n++ ) {
if (isPrime(n)) { // if its Prime, print and increase count
printf("%d\n", n);
count ++;
}
// Check next number until we get all our numbers
}
return 0; // All Done
}
This is your modified working code.
In each step you should re initializing primenumber=1 otherwise it gives only one number. Also count should be increases when you find a prime otherwise not.
#include <stdio.h>
int main() {
int n, i, count, primenumber = 1; // primenumber is a flag
printf("Insert a number:\n");
scanf("%d", &n);
for (count = 0, n++; count < 10; n++ ) {
primenumber = 1;
for (i = 2; i < n; i++) {
if (n % i == 0) {
primenumber = 0;
break;
}
}
if (primenumber){
count++;
printf("%d\n", n);
}
}
return 0;
}
Here is a solution which will reduce the processing time, generally used for larger values of n:
#include <stdio.h>
#include <math.h>
int main() {
int n, i, count= 1, primenumber = 1, root; // primenumber is a flag
printf("Insert a number:\n");
scanf("%d", &n);
n++;
while(count!=11)
{
root= sqrt(n);//You only need to check for range 2 to square root of number. This is the key ingredient of the code to reduce time complexity
primenumber = 1;
for(i=2; i<= root; i++)
{
if(n%i==0)//As soon as it finds a number which perfectly divides it, break from loop checking n's nature
{
primenumber = 0;
break;
}
}
if(primenumber==1)
{
printf("%d \t", n);
count++;
}
n++;
}
}

Resources