figure out the prime numbers between 0 and 1000? - c

I'm trying to make a programm that can calculate the prime numbers between 0 and 1000, the compiler says it has no warning and no erros too, but when i run the programm it gives me an execution error, i have no ideia what it is, does anybody could take a look at my code??
NOTE: i'm a beginner in programming.
#include <stdio.h>
#include <stdlib.h>
int main(){
int i=0;
for (i=0;i<1000;i++){
if (i % 1 == 0 && i % i == 0){
printf("%d",i );
}
printf(" ");
}
return 0;
}

You are performing a division by zero in
i % i == 0
for i = 0.
Moreover, even if you start you cycle from i = 1, the code will give you every integer between 1 and 999, for the expression
i % 1 == 0 && i % i == 0
is true whenever i != 0. Here is a fixed algorithm (not the most efficient, admittedly):
#include <stdio.h>
int main(){
int i; /* no need to initialize to zero */
int j; /* we need a second counter */
for (i=2;i<1000;i++){ /* start from 2 -- one is not prime */
for (j=2;j<i;j++){ /* check for nontrivial divisors */
if (i % j == 0) {
break; /* nontrivial divisor found -> not a prime */
}
}
if (j == i) { /* this means the cycle above run till end */
printf("%d ",i ); /* hence no nontrivial divisors, hence a prime */
}
}
printf("\n");
return 0;
}

The problem is with the expression i % i. In the first iteration of your loop, i is 0, so you are dividing by zero.

You should iterate from 1 to 1000, because dividing with 0 is not allowed and it gives floating point exception.
Also, your algorithm is not correct.
Use code from here:
http://www.programmingsimplified.com/c/source-code/c-program-for-prime-number

What happens when i is 0? My guess is you want to start your loop at 1 (as well as fix your prime number check).

Below python code may help you for following purposes:
To figure out the total number of primes in the range of 0 to given number (upper limit)
To know about each and every number whether that is prime or not
The Complete list of primes fall in the specified range
primes=[]
limit = int(input('What is the maximum limit?'))
for n in range(2,limit+1):
for x in range(2,n):
if n%x == 0:
print('{} -> Not prime'.format(n))
break
else:
primes.append(n)
print('{} -> Prime'.format(n))
print(primes)
print('Total {} primes found'.format(len(primes)))
If you don't want non-prime numbers to display then you can comment out #print('{} -> Not prime'.format(n)) this line and if you don't even want to know all primes comment the consecutive print statement as well i.e. #print('{} -> Prime'.format(n))

Related

is there a way to use Arrays in this C problem?

I am doing this problem:
"We have a huge decimal number N. Write a program to determine the followings:
The number of digits in N.
Is N an even number?
The number of zeros in it.
Is N a multiple of 11? Note that we can determine if N is a multiple of 11 by checking the difference between the sum of the odd positioned digits and the sum of the even positioned digits. For example, 82375 is not a multiple of 11 because the sum of the even positioned digits is 2 + 7 = 9, and the sum of the odd positioned digits is 8 + 3 + 5 = 16, and the difference between 9 and 16 is 7, which is not a multiple of 11.
We will give you the number one digit per line. For example, if you get digits ‘1’, ‘2’, ‘3’, ’4’, ‘0’ in order, then the number is 12340. The number will not start with 0.
Input Format
The input has several lines. Each line has a digit. EOF indicates the end of input.
Output Format
Output the four answers above line by line. If the number is even output a 1; otherwise a 0. If the number is a multiple of 11 output a 1; otherwise output a 0.
Subtask
10 points: you can store the decimal number in an integer without overflow
10 points: the number of digits is no more than 32768, so you can store digits in an array
80 points: you will get MLE if you use array"
my code is:
#include <stdio.h>
#include <stdbool.h>
int digit(long n);
int is_even(int n);
int count_zeros(long n);
int is_multiple(long n);
int main() {
int digits = 0;
long x;
scanf("%ld", &x);
digit(x);
int even = is_even(x);
printf("%d\n", even);
printf("%ld\n",count_zeros(x));
printf("%ld\n", is_multiple(x));
}
int digit(long n)
{
int digits = 0;
while (n > 0) {
n /= 10;
digits++;
}
printf("%ld\n", digits);
}
int is_even(int n)
{
if (n % 2 == 0)
return true;
else
return false;
}
int count_zeros(long n)
{
int count = 0;
while (n > 0) {
n /= 10;
if (n %10 == 0)
count++;
}
return count;
}
int is_multiple(long n)
{
if (n % 11 == 0) {
return true;
}
else
return false;
}
Basically i dont know how to meet the problem's requirement, so I made a simpler version of the problem. Any clue on how to do this?
If you comment on this, please be nice, I am a beginner and people was rude in the past,if you have nothing important to say, do not be mean/do not comment.
Well, the first problem with your current version is it only reads one integer. However problem states that each digit is on a separate line. The first approach may be to just replace that scanf with a loop and keeping multiplying by 10 and accumulating until end of file. Then the rest of the program would work fine.
A more advanced approach will be to use an array to store the digits. An integer can hold a very limited number of digits whereas you are only bounded with the size of available memory using array.
So in the reading loop rather than storing digits in an integer, you can store digits in an array (which could be fixed size because an upper limit is given). But for the rest of the program you should change the calculation to use digits in the array instead of the regular integer arithmetic.

For loop skipping numbers in C

I am trying to program a prime number checker in c but the following code returns some prime numbers as non prime. I haven't been able to find any non prime which register as prime. I am unsure where I have gone wrong and am beginning to suspect that my for loop is skipping numbers.
#include <stdio.h>
#include <stdlib.h>
int main() {
int nummer = 47203;
printf("Ist %d eine Primzahl?\n", nummer);
int dividey =2;
if (nummer == 2){
printf("nein");
}
for (dividey = 2; dividey <= nummer/2; dividey++){
if (nummer%dividey==0){
printf("nein");
break;
}else {
printf("ja");
break;
}
}
}
Yes, it is skipping numbers - because you've told it to!
If you were checking 15, for example - this is obviously not prime. On the first time through your loop, dividey is set to 2. You then do this check:
if (nummer%dividey==0)
15 % 2 is 1, so this condition fails and you jump to the else part.
Your else part does this:
printf("ja");
break;
I.e. it prints Ja to say it's a prime number and stops looping, even though it's not a prime and you haven't checked all of the divisors. If the loop had continued on to check dividing by 3, it would have realised it's not prime.

C Program crashes at For Loop

I'm new to C programming (I have some very basic experience with programming via vb.NET), and I'm attempting to write a program for the Project Euler Problem #1.
https://projecteuler.net/problem=1
Algorithm
The challenge requires the programmer to find the sum of all multiples of 3 or 5 (inclusive) below 1000 (I used intInput to allow the user to enter an integer in place of 1000).
My current solution takes the input, and decrements it by 1 until (intInput - n) % 3 = 0, that is, until the next nearest multiple of 3 under the input integer is found.
The program then cycles through all integers from 1 to ((intInput - n) / 3), adding each integer to the sum of the previous integers, so long as the current integer is not a multiple of 5, in which case, it is skipped.
The resultant sum is then stored in intThreeMultiplier.
The above process is then repeated, using 5 in place of 3 to find the highest multiple of 5 under intInput, and then cycles through integers 1 to ((intInput - n) / 5), not skipping multiples of 3 this time, and stores the sum in intFiveMultiplier.
The output sum is then calculated via sum = (3 * intThreeMultiplier) + (5 * intFiveMultiplier).
The Problem
Whenever I compile and run my code, the user is allowed to input an integer, and then the program crashes. I have determined that the cause has something to do with the first For loop, but I can't figure out what it is.
I have commented out everything following the offending code fragment.
Source Code:
#include <stdio.h>
#include <stdlib.h>
void main()
{
int intInput = 0; /*Holds the target number (1000 in the challenge statement.)*/
int n = 0;
int count = 0;
int intThreeMultiplier = 1;
int intFiveMultiplier = 1;
printf("Please enter a positive integer.\n");
scanf("%d",intInput);
for( ; (((intInput - n) % 3) != 0) ; n++)
{}
/*for(; count <= ((intInput - n) / 3); count++)
{
if ((count % 5) != 0)
{
intThreeMultiplier += count;
}
}
count = 0;
for(n = 0 ; ((intInput - n) % 5) != 0 ; n++)
{}
for(; count <= ((intInput - n) / 5) ; count++)
{
intFiveMultiplier += count;
}
int sum = (3 * intThreeMultiplier) + (5 * intFiveMultiplier);
printf("The sume of all multiples of 3 or 5 (inclusively) under %d is %d.",intInput, sum);*/
}
This is my first time posting on StackOverflow, so I apologize in advance if I have broken any of the rules for asking questions, and would appreciate any feedback with respect to this.
In addition, I am extremely open to any suggestions regarding coding practices, or any rookie mistakes I've made with C.
Thanks!
scanf("%d",intInput);
might be
scanf("%d", &intInput); // note the ampersand
scanf need the address the variable where the content is to be stored. Why scanf must take the address of operator
For debugging only, print the input to verify that the input is accepted correctly, something like
printf("intInput = %d\n", intInput);
The first thing you need when you are inputting intInput you should use:
scanf("%d", &intInput);
Because scanf() need as an argument of a pointer to your variable. You are doing this by just putting the & sign before your int.
In addition I think that you should double check your algorithm, because you are summing up some numbers more than once. :)

Can't Understand Code fragment

I cannot understand how the code is giving output of the prime factors of input..and what is the use of temp variable in this code?another question is what is the purpose of i=1 in the code fragment?
#include<stdio.h>
int main()
{
int number,i,temp;
scanf("%d",&number);
if(number<0)
{
printf("%d = -1 x ",number); //just printing
number=number*-1; //multiplication by -1
}
else
{
printf("%d = ",number); //just printing
}
for(i=2;i*i<=number;i++)
{
if(number%i==0)
{
printf("%d x ",i);
number=number/i;
temp=i;
i=1;
}
}
printf("%d\n",number);
return 0;
}
sample input:100
sample output:100 = 2 x 2 x 5 x 5
sample input:20
sample output:20 = 2 x 2 x 5
As previously mentioned, temp is unused.
The way this prints the prime numbers is by trying over and over to divide the number by the smallest number possible. That is the purpose of i=1.
So take 175.
First, the loop is initialized at 2. It then increments i until 175 % i == 0. When this happens, it means that i is a factor of 175. So it prints i and divides 175 by i. This ensures you won't double-count the factor. Here, this will happen first for i == 5. So now, num = 175/5 = 35.
At this point, i is reset to 1. The first thing that happens at the end of the loop block is that i is incremented to 2. So now again, it looks for the smallest factor. Again, it finds 5.
If i was not set to 1, the program would keep going up and it would miss the fact that 5 is a factor of 175 twice.
Eventually, when i > number, the program knows that it has found all the factors. This is because factors have to be less than the number they are factors of.
Hope this helps.
temp isn't used. i=1 resets the checking for factors at 1 once a factor is found
Here in this code..
i = 1
resets i as you want the prime factors.. else if it let to increment you will get values like 4 and 6 also.. which would be wrong.
no use of
temp = i;
Here temp variable is not used at all. You may remove it from pgm.
i=1 is done, so that checking of remainder if(number%i==0) can be started from value 2 again.

C Program Runs Surprisingly Slow

A simple program I wrote in C takes upwards of half an hour to run. I am surprised that C would take so long to run, because from what I can find on the internet C ( aside from C++ or Java ) is one of the faster languages.
// this is a program to find the first triangular number that is divisible by 500 factors
int main()
{
int a; // for triangular num loop
int b = 1; // limit for triangular num (1+2+3+......+b)
int c; // factor counter
int d; // divisor
int e = 1; // ends loop
long long int t = 0; // triangular number in use
while( e != 0 )
{
c = 0;
// create triangular number t
t = t + b;
b++;
// printf("%lld\n", t); // in case you want to see where it's at
// counts factors
for( d = 1 ; d != t ; d++ )
{
if( t % d == 0 )
{
c++;
}
}
// test to see if condition is met
if( c > 500 )
{
break;
}
}
printf("%lld is the first triangular number with more than 500 factors\n", t);
getchar();
return 0;
}
Granted the program runs through a lot of data, but none of it is ever saved, just tested and passed over.
I am using the Tiny C Compiler on Windows 8.
Is there a reason this runs so slowly? What would be a faster way of achieving the same result?
Thank you!
You're iterating over a ton of numbers you don't need to. By definition, a positive factor is any whole number that can be multiplied by another to obtain the desired product.
Ex: 12 = 1*12, 2*6, and 3*4
The order of multiplication are NOT considered when deciding factors. In other words,
Ex: 12 = 2*6 = 6*2
The order doesn't matter. 2 and 6 are factors once.
The square root is the one singleton that will come out of a factoring of a product that stands alone. All others are in pairs, and I hope that is clear. Given that, you can significantly speed up your code by doing the following:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
// this is a program to find the first triangular number that is divisible by 500 factors
int main()
{
int c = 0; // factor counter
long long int b = 0; // limit for triangular num (1+2+3+......+b)
long long int d; // divisor
long long int t = 0; // triangular number in use
long long int r = 0; // root of current test number
while (c <= 500)
{
c = 0;
// next triangular number
t += ++b;
// get closest root.
r = floor(sqrt(t));
// counts factors
for( d = 1 ; d < r; ++d )
{
if( t % d == 0 )
c += 2; // add the factor *pair* (there are two)
}
if (t % r == 0) // add the square root if it is applicable.
++c;
}
printf("%lld is the first triangular number with more than 500 factors\n", t);
return 0;
}
Running this on IDEOne.com takes less than two seconds to come up with the following:
Output
76576500 is the first triangular number with more than 500 factors
I hope this helps. (and I think that is the correct answer). There are certainly more efficient ways of doing this (see here for some spoilers if you're interested), but going with your code idea and seeing how far we could take it was the goal of this answer.
Finally, this finds the first number with MORE than 500 factors (i.e. 501 or more) as per your output message. Your comment at the top of the file indicates you're looking for the first number with 500-or-more, which does not match up with your output message.
Without any math analysis:
...
do
{
c = 0;
t += b;
b++;
for (d = 1; d < t; ++d)
{
if (!(t % d))
{
c++;
}
}
} while (c <= 500);
...
You are implementing an O(n^2) algorithm. It would be surprising if the code took less than a half an hour.
Refer to your computer science textbook for a better method compared to this brute force method of: check 1, 1 + 2, 1 + 2 + 3, etc.
You might be able to shorten the inner for loop. Does it really need to check all the way up to t for factors that divide the triangular number. For example, can 10 be evenly divisible by any number greater than 5? or 100 by any number greater than 50?
Thus, given a number N, what is the largest number that can evenly divide N?
Keep reading/researching this problem.
Also, as other people have mentioned, the outer loop could be simply coded as:
while (1)
{
// etc.
}
So, no need need to declare e, or a? Note, this doesn't affect the length of time, but your coding style indicates you are still learning and thus a reviewer would question everything your code does!!
You are doing some unnecessary operations, and I think those instructions are not at all required if we can check that simply.
first :
while(e!=0)
as you declared e=1, if you put only 1 in loop it will work. You are not updating value of e anywhere.
Change that and check whether it works fine or not.
One of the beautiful things about triangle numbers, is that if you have a triangle number, with a simple addition operation, you can have the next one.

Resources