Optimization with coding [closed] - c

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a program for prime numbers but I need to optimize it. Any hints?
int num, i, count = 0;
printf("Type a non-negative integer:\n");
scanf("%d", &num);
if((num%2 == 0 )&& (num != 2)||(num == 1)){
printf("%d is not a prime number.\n", num);
} else if(num == 2){
printf("%d is a prime number.\n", num);
} else {
for(i = 3; i < num; i += 2){
if(num%i == 0){
count++;
break;
}
}
if(count == 0){
printf("%d is a prime number.\n", num);
} else {
printf("%d is not a prime number.\n", num);
}
}
}

You only need to check up to the square root of num. See testing primes for some more hints.

I think this is one of the basic problems that you might solve it yourself!
I can help you to solve this problem; first start with having a look to the prime numbers definition:
A prime number is a number that is only diviible by 1 and itself.
Assume that we name it N then N is only divisible by 1 and N, and the number 1 is not prime.
So the idea is:
1 - if number is 1 is not prime !
2 - if number is 2 is prime
3 - else ----> we initialize i = 2 , then start calculating the value of N%i; if it is 0 the number is not prime, otherwise we must increment i by 1.
We do step 3 until i<N (or i<=sqrt(N) )
If the number is not divisible by any i, then it is prime!
Here is a simple implementation:
int n ;
printf("enter n:");
scanf("%d",&n);
if(n<=1) printf("is not prime");
else if(n==2) printf("is prime");
else{
bool flag = true;
for(int i = 2 ; i < n ; i++)
if( n%i==0 ){
flag = false;
break;
}
if(flag) printf("is prime");
else printf("is not prime");
}
There is a better algorithm to find a series of prime numbers; I think it's better to learn it:
Sieve of Eratosthenes
I hope this tutorial helps you to find out what is a prime number.

Related

Guessing game in C, cannot get the number of tries to work, variable is "counter" [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Not too sure how to make the counter variable work to count how many tries it takes to guess the number right. Ive tried putting "counter++;" in each if statement but that doesn't do anything. This is my first code that I've written by myself so don't drag it too hard please <3
int main()
int counter
{
int num , guess;
counter = 0;
srand(time(0));
num = rand() % 200 + 1;
printf ( "Guessing game, guess the number between 1 and 200" );
do {
scanf ( "%d" , &guess);
if ( guess > num ){
printf ( "Too high" );
}
if ( guess < num ){
printf ( "Too low" );
}
if ( guess == num ){
counter++;
printf ( "Your guess is correct!, it took you %d tries" , counter );
}
}while (guess != num);
return 0;
}
You only increment counter when the user guesses correctly. You should instead increment it for every try.
There are syntax errors in your program. Here is a corrected version:
#include <stdio.h>
int main() {
int counter = 0;
int num, guess;
srand(time(0));
num = rand() % 200 + 1;
printf("Guessing game, guess the number between 1 and 200");
while (scanf("%d", &guess) == 1) {
counter++;
if (guess > num) {
printf("Too high\n");
}
if (guess < num) {
printf("Too low\n");
}
if (guess == num) {
printf("Your guess is correct! it took you %d tries\n", counter);
return 0;
}
}
printf("Invalid input\n");
return 1;
}

what is wrong with this code? (to check whether a given number is a prime number) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
#include <stdio.h>
#include <conio.h>
void main() {
int a, n, x;
clrscr();
printf("enter a number");
scanf("%d", &a);
n > 1;
a != n && n < a;
if (a / n == x)
printf("a is not a prime no");
else
printf("a is a prime no");
}
If I run this and put a composite number, it still shows it as prime.
your if statement is never true duo to n and x are not initialized. Therefore you only get your else as return. Moreover your expression n>1; and a != n && n < a; return a bool which is not compered to anything. In that case you need to use a for loop.
Here is a link About for loops
int main()
{
int a,n,x = 0;
printf("enter a number: ");
scanf("%d",&a);
for(n=2; n<=a/2; ++n)
{
if(a%n==0)
{
x=1;
break;
}
}
if (x==0)
printf("",n);
else
printf("a is not a prime no");
return 0;
}
#include<stdio.h>
#include<conio.h>
int main()
{
clrscr();//clearing the screen
int n,x=2,count=0;//Here count is initialised to 0,if it is not prime it remains the same,else it will be equal to 1.You will understand this as you go down
//A number is a prime number if it is not divisible by any other number from 2 and the number before it.
printf("Enter a number : ");
scanf("%d",&n);
while(x<n)//As this checking process should continue till the number just preceding it
{
if(n%x==0)//checking if the number n is divisible by x or not
{
count++;//IF divisible,there is no meaning in continuing,So we are coming out of the loop by incrementing the variable "count"
break;
}
else
x++;
}
if(count==0)
{
printf("%d is a prime number",n);
return 0;//Here if number is prime,There is no need to go further and execute till end,To reduce time complexity ,We will write a return statement to stop executing the code.
}
printf("%d is not a prime number",n);
return 0;
}

Need help making prime numbers row in {c}

I need to make a program in {c} that would give me prime number for entered number (example is user enter 50. to write back 229)
So, I am stuck when making loop.
I am tring to define for row[100] to have row[0]=2,row[1]=3 and then I make i=4 and try to make a loop that would for number i devide number i with every single number in the row (becose those I know are prime numbers) and get module (number after 0,not sure how it is said on english), and then if if all of them have module !=0 then I know it is prime number and I want to add it into row.
So is there a way somebody can help me write this line? Thanks alot in advance :)
#include <stdio.h>
int main ()
{
int i,numb=4,position,temp,temp1,row[100];
printf(" enter position (1-100)\n");
scanf("%d",&position);
if (position>100||position<0 )
{
printf("error,enter position between 1 and 100");
return(0);
}
row[0]=2;
row[1]=3;
i=2;
do
{
temp=numb%2;
temp1=numb%3;
if (temp!=0 && temp1!=0)
{
row[i]=numb;
i++;
}
numb++;
}
while (i<100);
printf("%d. prime number is %d",position,row[position]);
return 0;
}
Ok,so I need to change part where I ask for module from deviding wit 2 and 3 to asking for module from deviding from all numbers in row at that moment. Thank you for help
#include <stdio.h>
#define MAX_N 100
int main(void){
int i, odd, temp, position, n = 0, row[MAX_N];
row[n++]=2;
row[n++]=3;
for(odd = 5; n < MAX_N; odd += 2){
int is_prime = 1;//true
for(i = 1; i < n; ++i){
temp = row[i];
if(temp * temp > odd)
break;
if(odd % temp == 0){
is_prime = 0;//false
break;
}
}
if(is_prime)
row[n++] = odd;
}
printf(" enter position (1-%d)\n", MAX_N);
scanf("%d", &position);
if (position > 100 || position < 1){
printf("error,enter position between 1 and %d\n", MAX_N);
return 0;
}
printf("%d. prime number is %d", position, row[position - 1]);
return 0;
}

C programming about scanf and array [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I try to make this program when I enter 3 5 2 5 5 5 0
=>
Enter numbers: 3 5 2 5 5 5 0
The largest number is 5
The occurrence count of the largest number is 4
int main()
{
int a[10];
int i,max, count;
printf("Enter numbers: ");
for(i=0;i<10;i++)
{
scanf("%d",&a[i]);
}
max=a[0];
count=1;
for(i=1;i<10;i++)
{
if(max<a[i])
{
count = 1;
max = a[i];
}
else if(max==a[i])
{
count++;
}
}
printf("The largest number is %d\n",max);
printf("The occurrence count of the largest number is %d",count);
return 0;
}
It is my code, but it is totally wrong..
I don't know what should I do
please help me
You've got several errors.
In your first loop, you want to read into a[i], not a[10].
Your code corrently assumes you always type in 10 numbers. It looks like you wanted a value of 0 to end the list. Me, I'd use end-of-file to end the list. To check for 0 you need an extra line if(a[i] == 0) break; in the loop. To check for EOF (or other non-numeric input which will cause problems) you could check to see that scanf returns 1.
In case you enter less than 10 numbers, you'll need a new variable that knows how many variables you actually entered. I set nn = i after the first loop.
Then you just need to change the second loop to run from 1 to nn, not 10.
Putting this all together, we have:
#include <stdio.h>
int main()
{
int a[10];
int i,max, count, nn;
printf("Enter numbers: ");
for(i=0;i<10;i++)
{
if(scanf("%d",&a[i]) != 1) break;
if(a[i] == 0) break;
}
nn = i;
max=a[0];
count=1;
for(i=1;i<nn;i++)
{
if(max<a[i])
{
count = 1;
max = a[i];
}
else if(max==a[i])
{
count++;
}
}
printf("The largest number is %d\n",max);
printf("The occurrence count of the largest number is %d\n",count);
return 0;
}
This seems to work.
Code is OK other than the user needs to enter 10 numbers.
There is no need to store previous numbers, so code can simply examine each new number until '\n' is encountered. Just keep look for the end-of-line before looking for the number.
#include <limits.h>
#include <stdio.h>
#include <ctype.h>
int main(void) {
int count = 0;
int max = INT_MIN;
printf("Enter numbers: ");
for (;;) {
int ch;
int num;
while (isspace(ch = fgetc(stdin)) && ch != '\n') {
;
}
if (ch == '\n' || ch == EOF) break;
ungetc(ch, stdin);
if (scanf("%d", &num) != 1) break;
if (num >= max) {
count++;
if (num > max) {
max = num;
count = 1;
}
}
}
printf("The largest number is %d\n", max);
printf("The occurrence count of the largest number is %d", count);
return 0;
}

Prime Number Check 1-100 (C) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
The code below is to read input from the user to check if an int [1-100] is a prime number or not. (If out of range, will print "Done). If non prime, will output that to the console and the number divisible.
Right now this program is running correctly for 1-10 except for 3 and 9... Any suggestions?
#include <stdio.h>
int main()
{
int num, i;
printf("Number [1-100]:? \n");
scanf("%d", &num);
while(num>0 && num <101)
{
if (num==1||num==2)
printf("Prime\n");
for (i=2; i<=num/2; ++i)
{
if (num%i==0)
{
printf("Non-prime,divisible by %d\n",i);
break;
}
else {
printf("Prime\n");
break;
}
}
printf("Number[1-100]:? \n");
scanf("%d",&num);
}
printf("Done\n");
}
First, make sure your code has appropriate whitespace. This will help you realize when things aren't lined up like you think they are.
#include <stdio.h>
int main()
{
int num, i;
printf("Number [1-100]:? \n");
scanf("%d", &num);
while(num>0 && num <101){
if (num==1||num==2)
printf("Prime\n");
for(i=2; i<=num/2; ++i)
{
if (num%i==0)
{
printf("Non-prime,divisible by %d\n",i);
break;
}
else {
printf("Prime\n");
break;
}
}
printf("Number[1-100]:? \n");
scanf("%d",&num);
}
printf("Done\n");
}
Now you should realize that your else statement happens on the first check! So when 3 is not divisible by 2, it prints "prime."
And then it breaks out of the loop.
And this happens for EVERY number. All your program is doing is checking to see if numbers are divisible by 2.
If you wrote "Odd" instead of "Prime" it would at least be correct there.
This is the kind of problem where setting a flag might be useful (there are other ways to do this, but this is one way).
So you could set a flag, say int isPrime = 1;
Now, if you find out that the number is not prime, you simply set isPrime = 0;.
Finally, at the end of the for loop (let me repeat: AFTER the for loop finishes), you need to check that variable.
And you can say,
if (isPrime == 1)
{
printf("Prime\n");
} else
{
printf("Non-prime.");
}
I'll let you figure out how to print the divisor :)
(For reference, correctly using the flag would look like this -- and for clarity I removed the 'feature' in which it continuously looped)
#include <stdio.h>
int main()
{
int num, i;
int isPrime = 1;
printf("Number [1-100]:? \n");
scanf("%d", &num);
for(i=2; i<=num/2; ++i)
{
if (num%i==0)
{
isPrime = 0;
break;
}
}
if (isPrime == 1)
{
printf("Prime\n");
} else
{
printf("Non-prime.");
}
printf("Done\n");
}
The reason why 3 is behaving differently is that the for logic never reaches 3. For "(i=2; i <= num/2; ++i)", if num equals 3, then the i (being 2) is no longer less than 3/2, which is 1 (after rounding off). So, you should add "num==3" check to the "if (num==1||num==2)".
You're not checking the entire range between 2 and num/2. You need a while loop and a prime flag.
Something like this.
while(num>0 && num <101)
{
unsigned char prime = 1; // set prime flag
i = 2;
while( i < (num/2)+1)
{
if(num%i == 0)
prime = 0;
i++;
}
if(num == 1)
prime = 0;
if(prime == 0)
printf("%d is nonprime\n", num);
else
printf("%d is prime\n", num);
prime = 1;
printf("Number[1-100]:? \n");
scanf("%d",&num);
}

Resources