I had to develop a program using c that takes as input 2 different number from user and output prime number with in the input(eg input 2 and 100 , output as prime number from2 to 100). The program should terminate non prime number and do not print.
Anyone please tell me the error in the code
setbuf(stdout,NULL);
int flag=0,num,num1,i,a;
printf("Enter 2 number");
scanf("%d%d",&num,&num1);
for(i=num;i<=num1;i++){
for(a=2;a<i;a++){
if(i%a==0){
flag=1;
break;
}
if(flag==0){
printf("\n%d",num);
}
}
}
I had to develop a program using c that takes as input 2 different number from user and output prime number with in the input(eg input 2 and 100 , output was prime number from 2 to 100). The program should terminate non prime number and do not print.
At least this issue:
int flag=0 should be inside the for(i=num;i<=num1;i++){ loop to reset the prime detection for each new i.
Note: for(a=2; a<=i/a; a++) { much faster than for(a=2;a<i;a++){
Related
printf("enter number:");
scanf("%d",&number);
for(i=2;i<number;i++){
if(number%i==0)
printf("your number isn't prime\n");
else
printf("your number is prime\n");
}
I wrote this code. The code runs but if I enter 10, it is printing many times that it isn't prime.
Tip 1: try using a flag (but code would become longer,unnecessarily!)
Tip 2: simply put a break statement after your first printf ;)
as mentioned in the comment by DyZ you should break the loop once you know that the number is not a prime and only report that the number is prime AFTER the loop.
Additionally you do not have to check multiples of already checked divisors. if your number is not divisible by 2 it is not divisible by any multiple of 2 like 4, 6, 8 and so on.
also, check following already answered question on prime numbers
Getting time limit exceeded on submitting answer. I am also facing same problem with 2-3 more questions that I have submitted on spoj.com.
http://www.spoj.com/problems/PRIME1/
Peter wants to generate some prime numbers for his cryptosystem. Help him! Your task is to generate all prime numbers between two given numbers!
Input
The input begins with the number t of test cases in a single line (t<=10). In each of the next t lines there are two numbers m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space.
Output
For every test case print all prime numbers p such that m <= p <= n, one number per line, test cases separated by an empty line.
Example
Input:
2
1 10
3 5
Output:
2
3
5
7
3
5
Warning: large Input/Output data, be careful with certain languages (though most should be OK if the algorithm is well designed)
Here is my code in C.
#include <stdio.h>
int main()
{
int t,i,k,count;
long long int j=0,m=0,n=0;
scanf("%d",&t);
for(i=1;i<=t;i++)
{
scanf("%lld%lld",&m,&n);
for(j=m;j<=n;j++)
{
count=0;
for(k=1;k<=j/2;k++)
{
if(j%k==0)
count++;
if(count>1)
break;
}
if(count==1)
printf("%lld\n",j);
}
printf("\n");
}
return 0;
}
Your algorithm is O((m-n)*n) which of course won't run within the allocated time limit. Let's go over your code:
count=0;
for(k=1;k<=j/2;k++)
{
if(j%k==0)
count++;
if(count>1)
break;
}
if(count==1)
printf("%lld\n",j);
Micro optimization: Why do you need a counter? You could get away with a bool.
Optimization: Why are you testing primes j/2? If j has a divisor greater than 1 than it's guaranteed that j has a divisor that's at most sqrt(j).
Micro Optimization: Don't consider even numbers at all, except for 2.
bool prime = j==2 || j%2==1 ;
for(k=2;prime && k*k<=j;k++)
{
if(j%k==0) prime = false;
}
}
if(prime) printf("%lld\n",j);
Now this is O((m-n)*sqrt(n)) which is a lot faster.
I suppose this won't make the limit. You could extend the second micro-optimization to skip numbers divisible by 3 very easy.
Optimization: If this is still not enough then you have to do a pseudo-primality test. One test that's very easy to implement in O(log(n)) is https://en.wikipedia.org/wiki/Fermat_primality_test. With this the complexity is down to O((m-n)*log(n)) which should be run in the available time limit.
Key points, I'm using Codeblocks to write this program, and it needs to be written with the intent of writing C only and nothing more. I want it to be as basic as possible. So this is the mess that I have so far.
I need this program to continue to ask the user for a value until between 1-29 until it reaches 176. Once it exceeds 176 all I need to do is print the sum of the numbers, the largest number entered and the smallest number entered.
From there the program needs to loop and ask if another set of numbers will be entered. Terminating the program with the appropriate user input. I need to output the following info:
Sum of all numbers
Largest number entered
smallest number entered
If anyone has any advice that would help a lot.
/* Matthew Gambrell CSC 120 12/4/14*/
#include <stdio.h>
main ()
{
int total, num, large, small, again;
again=1;
while (again==1);
{
total = 0;
large = 0;
small = 50;
}
while(total<=176);
{
num=inputNum();
total=tot(num, total);
large=CheckLarge(num, total);
small=CheckSmall(num, small);}
printresult(total, large, small);
printf("play again");
printf("1=yes 0=no");
scanf("%d", &again);
}
float inputNum();
{
float badnum, num;
badnum=1;
while (badnum==1);
printf("please enter a number between 1 and 29");
scanf("%f", &num);
if(num>0 and num<30)
badnum = 0;
else
printf("error renter");
getch("press enter to continue");
return(num)
}
tot(num, total)
total += num
return (total)
}
return(num)
Like your classmate said, you can do this using a loop within a loop. The structure of your code makes it seem like this was your goal.
Firstly, as mentioned in the comments, remove your semicolons from the end of your while(..); statements. This will allow control to enter the blocks you're defining below them.
Secondly, you probably want to place the closing bracket for your first while loop after the end of your second while loop. This is your 'loop within a loop' structure.
Thirdly, you don't have any real way of displaying your results at present. Usually, your int main(){ ... } function returns a number relating to how your program went. Whilst you can have it return your total variable, it's more likely you want it to return 0;, and output your variables to screen during program execution.
For example, as you did in your input parsing in inputNum(..), you can write
printf('The total is %i\n', total);
printf('The largest number entered was %i\n', large);
printf('The smallest number entered was %i\n', small);
These numbers (large and small) will need to be within your (first) while loop - they should be reset each time your loop restarts, but not each time you enter a number.
Example input: 20 10 5 20 2 20 20 20 2 2 0
Output:
(20*5)
(10*1)
(5*1)
(2*3)
I just started programming this semester and need help on a project. I apologize if my question is unclear.
So basically I have to input positive integers till I enter "0" would end the program. I'm not allowed to use arrays(whatever that means).
#include <stdio.h>
int main ()
{
int number, count=0
while(1)
{
scanf("%d",&number);
if (number!=0)
{
count++; continue;
}
else
{
printf("%d*%d",number,count);
break;
}
return 0;
}
How do I store these multiple numbers so that I wouldn't overlap the previous number and to increment duplicate numbers by 1 every time it's entered? I can't ask my professor for help; he just tells me to google it.
"A certain engineering apparatus is controlled by the input of successive numbers (integers).
If there is a run of the same number, the apparatus can optimize its performance. Hence we
would like to arrange the data so as to indicate that a run is coming. Write a C program that
reads a sequence of numbers and prints out each run of numbers in the form (n∗m) where
m is the number repeated n times. Note that a run can consist of just a single number. The
input numbers are terminated by a zero, which halts the apparatus."
This assignment seems to be based on half-baked knowledge of run length encoding (RLE). Anyway, here's a pseudo-code which does what it asks.
in = read next number from input
current_num = in // let the 1st number in list be current_num
count = 1
loop
in = read next number from input
if (in == 0) break // we are done, get out of loop
else if (in == current_num) count += 1
else // run has ended, print it and start new run
print current_num * count
current = in
count = 1
end loop
print current_num * count // we exited the loop before printing the last run
// so do it outside the loop
You can implement it in code and then "optimize" it to remove repeated code, and take care of corner cases (such as "empty" input, single number input, etc.)
Edit Just to be clear, the assignment asks for a 'run' of numbers, but the sample output shows a 'count' of numbers. These two are not the same.
Write a program that sums the sequence
of integers as well as the smallest in
the sequence. Assume that the first
integer read with scanf specifies the
number of values remaining to be
entered. For example the sequence
entered:
Input: 5 100 350 400 550 678
Output: The sum of the sequence of
integers is: 2078
Input: 5 40 67 9 13 98
Output: The smallest of the integers
entered is: 9
This is a daily problem I am working on but by looking at this, Isnt 5 the smallest integer? I have no idea how to write this program. Appreciate any help
First thing, the 5 is not considered part of the list, it's the count for the list. Hence it shouldn't be included in the calculations.
Since this is homework, here's the pseudo-code. Your job is to understand the pseudo-code first (run it through your head with sample inputs) then turn this into C code and try to get it compiling and running successfully (with those same sample inputs).
I would suggest the sample input of "2 7 3" (two items, those being 7 and 3) as a good start point since it's small and the sum will be 10, smallest 3.
If you've tried to do that for more than a day, then post your code into this question as an edit and we'll see what we can do to help you out.
get a number into quantity
set sum to zero
loop varying index from 1 to quantity
get a number into value
add value to sum
if index is 1
set smallest to value
else
if value is less than smallest
set smallest to value
endif
endif
endloop
output "The sum of the sequence of integers is: ", sum
output "The smallest of the integers entered is: ", smallest
Stack Overflow seems to be divided into three camps, those that will just give you the code, those that will tell you to push off and do your own homework and those, like me, who would rather see you educated - by the time you hit the workforce, I hope to be retired so you won't be competing with me :-).
And before anyone picks holes in my algorithm, this is for education. I've left at least one gotcha in it to help train the guy - there may be others and I will claim I put them there intentionally to test him :-).
Update:
Robert, after your (very good) attempt which I've already commented on, this is how I'd modify your code to do the task (hand yours in of course, not mine). You can hopefully see how my comments modify the code to reach this solution:
#include <stdio.h>
int main (int argCount, char *argVal[]) {
int i; // General purpose counter.
int smallNum; // Holds the smallest number.
int numSum; // Holds the sum of all numbers.
int currentNum; // Holds the current number.
int numCount; // Holds the count of numbers.
// Get count of numbers and make sure it's in range 1 through 50.
printf ("How many numbers will be entered (max 50)? ");
scanf ("%d", &numCount);
if ((numCount < 1) || (numCount > 50)) {
printf ("Invalid count of %d.\n", numCount);
return 1;
}
printf("\nEnter %d numbers then press enter after each entry:\n",
numCount);
// Set initial sum to zero, numbers will be added to this.
numSum = 0;
// Loop, getting and processing all numbers.
for (i = 0; i < numCount; i++) {
// Get the number.
printf("%2d> ", i+1);
scanf("%d", ¤tNum);
// Add the number to sum.
numSum += currentNum;
// First number entered is always lowest.
if (i == 0) {
smallNum = currentNum;
} else {
// Replace if current is smaller.
if (currentNum < smallNum) {
smallNum = currentNum;
}
}
}
// Output results.
printf ("The sum of the numbers is: %d\n", numSum);
printf ("The smallest number is: %d\n", smallNum);
return 0;
}
And here is the output from your sample data:
pax> ./qq
How many numbers will be entered (max 50)? 5
Enter 5 numbers then press enter after each entry:
1> 100
2> 350
3> 400
4> 550
5> 678
The sum of the numbers is: 2078
The smallest number is: 100
pax> ./qq
How many numbers will be entered (max 50)? 5
Enter 5 numbers then press enter after each entry:
1> 40
2> 67
3> 9
4> 13
5> 98
The sum of the numbers is: 227
The smallest number is: 9
pax> ./qq
How many numbers will be entered (max 50)? 0
Invalid count of 0.
[fury]$ ./qq
How many numbers will be entered (max 50)? 51
Invalid count of 51.
By the way, make sure you always add comments to your code. Educators love that sort of stuff. So do developers that have to try to understand your code 10 years into the future.
Read:
Assume that the first integer read
with scanf specifies the number of
values remaining to be entered
so it's not part of the sequence...
for the rest, it's your homework (and C...)
No. 5 is the number of integers you have to read into the list.
Jeebus, I'm not doing your homework for you, but...
Have you stopped to scratch this out on paper and work out how it should work? Write some pseudo-code and then transcribe to real code. I'd have thought:
Read integer
Loop that many times
** Read more integers
** Add
** Find Smallest
IF you're in C look at INT_MAX - that will help out finding the smallest integer.
Since the list of integers is variable, I'd be tempted to use strtok to split the string up into individual strings (separate by space) and then atoi to convert each number and sum or find minimum on the fly.
-Adam
First you read the number of values (ie. 5), then create an array of int of 5 elements, read the rest of the input, split them and put them in the array (after converting them to integers).
Then do a loop on the array to get the sum of to find the smallest value.
Hope that helps
wasn[']t looking for you guys to do the work
Cool. People tend to take offense when you dump the problem text at them and the problem text is phrased in an imperative form ("do this! write that! etc.").
You may want to say something like "I'm stuck with a homework problem. Here's the problem: write a [...]. I don't understand why [...]."
#include <stdio.h>
main ()
{
int num1, num2, num3, num4, num5, num6, i;
int smallestnumber=0;
int sum=0;
int numbers[50];
int count;
num1 = 0;
num2 = 0;
num3 = 0;
num4 = 0;
num5 = 0;
num6 = 0;
printf("How many numbers will be entered (max 50)? ");
scanf("%d", &count);
printf("\nEnter %d numbers then press enter after each entry: \n", count);
for (i=0; i < count; i++) {
printf("%2d> ", i+1);
scanf("%d", &numbers[i]);
sum += numbers[i];
}
smallestnumber = numbers[0];
for (i=0; i < count; i++) {
if ( numbers[i] < smallestnumber)
{
smallestnumber = numbers[i];
}
}
printf("the sum of the numbers is: %d\n", sum);
printf("The smallest number is: %d", smallestnumber);
}