I'm trying to print prime numbers between 0 and 100 but my code ends up giving 2,3 and every number from 5 to 99. What am I doing wrong?
#include <stdio.h>
#include<math.h>
void main()
{
int n=0,i=2,flag;
while(n<=100){
if(n<2){flag=0;}
else if(n==2 || n==3){printf("%d\n",n);}
else{
while(i<=sqrt(n)){
if(n%i==0){flag=0;break;}
else{flag=1;}
i++;//at this point no. is prime
}
if(flag==1){printf("%d\n",n);}
}
n++;
}
}
Rather than testing inside the loop for n==2 || n==3, you should just print the values 2 and 3 outside the loop, and start the loop at 5. Since no even numbers are prime after 2, only test odd numbers starting at 5. And you need to start testing for factors starting at i=3 (since you know they're not even you don't have to test 2). And you shouldn't check the value of flag (for primality) until the i-loop is done.
#include <stdio.h>
#include <math.h>
int main(void)
{
printf("2\n3\n");
for (int n = 5; n <= 100; n+= 2) {
int flag = 1;
for (int i = 3; i <= sqrt(n); ++i) {
if (n % i == 0) {
flag = 0;
break;
}
}
if (flag == 1)
printf("%d\n",n);
}
}
Related
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a,b,c;
b=1;
a=0;
scanf("%d", &a);
while (a>0)
{
c=a%10;
if (c==0)
b=b*1;
else {
b=b*(a%10);
a=a/10;
}
}
printf("Proizvedenie: %d\n", b);
return 0;
}
It doesnt work when I add 0 in any position of number, but i added if and dont know why it doesnt work, cycle just does not end, pls help
01234 - 24; Right
1234 - 24; Right
12304 - doesnt work
12340 - doesnt work
WHY PLS HELP =(
You're only dividing a by 10 when the current digit is not 0. When the digit is 0 a stays the same and you and up in an infinite loop.
Move the update of a to outside of the if block. Also, b=b*1 is a no-op, so you can remove that.
while (a>0)
{
c=a%10;
if (c!=0) {
b=b*c;
}
a=a/10;
}
You're only doing a = a/10 in the else block. So when you get to a 0 digit, you stop dividing by 10 and get stuck in an infinite loop.
Take that line out of the if/then, since it needs to be done every time.
while (a>0)
{
c=a%10;
if (c!=0) {
b *= c;
}
a /= 10;
}
unsigned int product(int x)
{
int result = !!x;
while(x)
{
if(x % 10) result *= abs(x % 10);
x /= 10;
}
return result;
}
int main(void)
{
int testData[] = {0, 1234, 12304, 12340, -1234, -12304, -012340 /* <- octal number!! */};
for(int x = 0; x < sizeof(testData)/sizeof(testData[0]); x ++)
printf("%d - %u\n", testData[x], product(testData[x]));
}
https://godbolt.org/z/T8T1a5YEE
Use functions.
integers can be negative as well
You need to handle zero too.
In your code:
c=a%10;
if (c==0)
b=b*1;
else {
b=b*(a%10);
a=a/10;
}
you need to move a = a / 10 outside the if as it is only executed when a % 10 is not zero. If it is, a does not change and you are in an infinitive loop
Others have noted the flaw in your code (location of a=a/10; inside else code block.
Here is a branchless way to achieve your objective. "Branching" (using an if() conditional) can make code run much slower when the processor's pipeline prediction turns out to be wrong. When processing millions (or billions) of data items, this may be a significant cost in time.
#include <stdio.h>
#include <stdlib.h>
int main() {
int a = 0, prod = 1;
if( scanf( "%d", &a ) != 1 ) {
fprintf( stderr, "scanf failed\n" );
return 1;
}
for( a = abs(a); a; a /= 10 ) {
int r = a%10;
prod *= r+(r==0); // branchless technique
}
printf( "Proizvedenie: %d\n", prod );
return 0;
}
54300012
Proizvedenie: 120
When the value of r is one of 1-9, r==0 has the value 0.
When the value of r is 0 and r==0 has the value 1.
So the 10 different rhs values can be 1, 1, 2, 3, 4, 5, 6, 7, 8 or 9.
I think the problem is with the for-loop but I cannot understand it. This is an assignment in school that I only should use for-loops and if statements to solve!
#include <stdio.h>
int is_prime(int n){
for (int i=2;i<n;i++){
if (n%i!=0){
return 1;
}
else{
return 0;
};
};
}
int main(void){
printf("%d\n", is_prime(11)); // 11 is a prime. Should print 1.
printf("%d\n", is_prime(383)); // 383 is a prime. Should print 1.
printf("%d\n", is_prime(987)); // 987 is not a prime. Should print 0.
}
For starters the null statement after the if statement and the for loop itself
for (int i=2;i<n;i++){
if (n%i!=0){
return 1;
}
else{
return 0;
};
^^^
};
^^^
is redundant.
Due to the if statement the for loop is interrupted as soon as either n % i is not equal to 0 or is equal to 0. So in general the behavior of the function does not depend on whether the passed number is prime or not prime.
If you will move the return statement
return 1;
outside the loop as others advised nevertheless the function will be still incorrect. It will show that 0 and 1 are prime numbers while they are not.
Also the condition of the loop makes the loop inefficient at least because it is clear before entering the loop that any even number except 2 is not a prime number.
Pay attention to that the function parameter should have unsigned integer type.
The function can be defined the following way
#include <stdio.h>
int is_prime( unsigned long long int n )
{
int prime = n % 2 == 0 ? n == 2 : n != 1;
for ( unsigned long long int i = 3; prime && i <= n / i; i += 2 )
{
prime = n % i != 0;
}
return prime;
}
int main(void)
{
printf( "%d\n", is_prime( 11 ) );
printf( "%d\n", is_prime( 383 ) );
printf( "%d\n", is_prime( 987 ) );
return 0;
}
The program output is
1
1
0
The problem is return 1 inside the loop. When you find one i that is not a factor of n, you assume n to be prime. But you have to ensure that all i are not a factor of prime, so the return 1 must be placed after the loop. However, that would cause numbers < 2 to be considered prime, as they do not enter the loop at all. Therefore, you also have to add an additional if at the beginning.
By the way: Every divisor of n (expect n itself) must be <= sqrt(n), therefore you can speed up your function quite a bit.
#include <math.h>
int is_prime(int n) {
if (n < 2)
return 0;
int max_divisor = sqrt(n);
for (int i = 2; i <= max_divisor; i++) {
if (n % i == 0)
return 0;
}
return 1;
}
Problem: return statement
return 1;
}
else{
return 0;
It causes the loop to exit then and there. In your case too, it exits as soon as the first '1' is achieved.
Solution: Instead you should try to store the values in a variable and compare with '1' or '0' at the end of loop
I have to write a program that finds every number (except 0) which can be factored by numbers from 2-9.
For example first such a number would be number 2520 as it can be divided by every single number from 2 to 9.
It also has to be a number that contains only 1 type of digit of its own (no multiple digits in a number). So for example 2520 will not meet this requirement since there are two same digits (2). The example of a number that meets both requirements is number 7560. That is the point I don't how to do it. I was thinking about converting value in an array to string, and then putting this string in another array so every digit would be represented by one array entry.
#include <stdio.h>
#include <math.h>
int main() {
int i, n, x, flag, y = 0;
scanf("%d", &n);
double z = pow(10, n) - 1;
int array[(int)z];
for (i = 0; i <= z; i++) {
flag = 0;
array[i] = i;
if (i > 0) {
for (x = 2; x <= 9; x++) {
if (array[i] % x != 0) {
flag = 1;
}
}
if (flag == 0) {
y = 1;
printf("%d\n", array[i]);
}
}
}
if (y == 0) {
printf("not exist");
}
return 0;
}
This should give you a base:
#include <stdio.h>
#include <string.h>
int main()
{
char snumber[20];
int number = 11235;
printf("Number = %d\n\n", number);
sprintf(snumber, "%d", number);
int histogram[10] = { 0 };
int len = strlen(snumber);
for (int i = 0; i < len; i++)
{
histogram[snumber[i] - '0']++;
}
for (int i = 0; i < 10; i++)
{
if (histogram[i] != 0)
printf("%d occurs %d times\n", i, histogram[i]);
}
}
Output:
Number = 11235
1 occurs 2 times
2 occurs 1 times
3 occurs 1 times
5 occurs 1 times
That code is a mess. Let's bin it.
Theorem: Any number that divides all numbers in the range 2 to 9 is a
multiple of 2520.
Therefore your algorithm takes the form
for (long i = 2520; i <= 9876543210 /*Beyond this there must be a duplicate*/; i += 2520){
// ToDo - reject if `i` contains one or more of the same digit.
}
For the ToDo part, see How to write a code to detect duplicate digits of any given number in C++?. Granted, it's C++, but the accepted answer ports verbatim.
If i understand correctly, your problem is that you need to identify whether a number is consisted of multiple digits.
Following your proposed approach, to convert the number into a string and use an array to represent digits, i can suggest the following solution for a function that implements it. The main function is used to test the has_repeated_digits function. It just shows a way to do it.
You can alter it and use it in your code.
#include <stdio.h>
#define MAX_DIGITS_IN_NUM 20
//returns 1 when there are repeated digits, 0 otherwise
int has_repeated_digits(int num){
// in array, array[0] represents how many times the '0' is found
// array[1], how many times '1' is found etc...
int array[10] = {0,0,0,0,0,0,0,0,0,0};
char num_string[MAX_DIGITS_IN_NUM];
//converts the number to string and stores it in num_string
sprintf(num_string, "%d", num);
int i = 0;
while (num_string[i] != '\0'){
//if a digit is found more than one time, return 1.
if (++array[num_string[i] - '0'] >= 2){
return 1; //found repeated digit
}
i++;
}
return 0; //no repeated digits found
}
// test tha function
int main()
{
int x=0;
while (scanf("%d", &x) != EOF){
if (has_repeated_digits(x))
printf("repeated digits found!\n");
else
printf("no repeated digits\n");
}
return 0;
}
You can simplify your problem from these remarks:
the least common multiple of 2, 3, 4, 5, 6, 7, 8 and 9 is 2520.
numbers larger than 9876543210 must have at least twice the same digit in their base 10 representation.
checking for duplicate digits can be done by counting the remainders of successive divisions by 10.
A simple approach is therefore to enumerate multiples of 2520 up to 9876543210 and select the numbers that have no duplicate digits.
Type unsigned long long is guaranteed to be large enough to represent all values to enumerate, but neither int nor long are.
Here is the code:
#include <stdio.h>
int main(void) {
unsigned long long i, n;
for (n = 2520; n <= 9876543210; n += 2520) {
int digits[10] = { 0 };
for (i = n; i != 0; i /= 10) {
if (digits[i % 10]++)
break;
}
if (i == 0)
printf("%llu\n", n);
}
return 0;
}
This program produces 13818 numbers in 0.076 seconds. The first one is 7560 and the last one is 9876351240.
The number 0 technically does match your constraints: it is evenly divisible by all non zero integers and it has no duplicate digits. But you excluded it explicitly.
A twin prime is a prime number that is exactly two larger than the largest prime number that is smaller than it. For example, 7 is a twin prime because it is exactly two larger than 5. But 17 is not a twin prime because the largest prime less than 17 is 13.
My logic for this program is as follows:
*ask number of twin primes that want to be found
*loop until desired number of twin primes are found
*loop numbers 2 - 1million (declared as variable j)
*check if that number 'j' is prime - if so flag it
*if 'j' is not flagged, subtract 2 from 'j' (call that new number 'TPcheck')
*Check if 'TPcheck' is a prime, if so, print 'TPcheck' and the first number 'j'
When I run this program, I enter the number of twin primes to be found, but it just continues to run, and doesn't print anything on the screen. I think that the problem may have something to do with the order of the loops and if statements(or maybe the way that they are nested), but I have tried a ton of different ways and nothing has worked.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i = 2, count = 0, TPcheck, j, k, flag;
int numberofTwinPrimes;
printf("Enter how many twin primes you want to find");
scanf("%d", &numberofTwinPrimes);
while(count < numberofTwinPrimes)
{
for(j = 2; j <= 1000000; ++j)
{ for(i = 2; i < j; ++i)
{
if(j%i == 0)
{
flag = 1;
continue;
}
if(flag == 0)
{
TPcheck = j - 2;
for(k = 2; k < TPcheck; ++k)
{
if(TPcheck%k == 0)
{
flag = 1;
continue;
}
if(flag == 0)
{
printf("%d\t %d\t", TPcheck, j);
count++;
}
}
}
}
}
}
return 0;
}
I think your code can be simplified quite a bit.
Define a function that simply returns whether a number is a prime number or not.
Use that in a loop using a very simple logic.
Here's a working version.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int isPrime(int n)
{
int stop = 0;
int i = 0;
// Special case for 3.
if ( n == 3 )
{
return 1;
}
// If n is not divisible by numbers up to sqrt(n),
// then, n is a prime number.
stop = (int)(sqrt(n));
// We can start at 3 and increment by 2
// There is no point dividing by even numbers.
for ( i = 3; i <= stop; i +=2 )
{
if ( n%i == 0 )
{
// It is not a prime number.
return 0;
}
}
// Checked divisibility by all numbers up to sqrt(n)
// This is a prime number.
return 1;
}
int main()
{
int i = 0;
int count = 0;
int numberofTwinPrimes;
printf("Enter how many twin primes you want to find: ");
scanf("%d", &numberofTwinPrimes);
// Start checking at 3 and increment by 2.
// There is no point checking even numbers.
// When we find the required number of twin primes, stop.
for(i = 3; i <= 1000000 && count < numberofTwinPrimes; i += 2 )
{
if ( isPrime(i) && isPrime(i+2) )
{
++count;
printf("%d\t %d\n", i, i+2);
}
}
return 0;
}
Here's the output when numberOfTwinPrimes is 10.
3 5
5 7
11 13
17 19
29 31
41 43
59 61
71 73
101 103
107 109
This isPrime() function is faster than Fumu's suggestion:
/* function isPrime returns True if argument is prime number. */
boolean isPrime(int aNumber)
{
int i;
int limit;
/* Numbers < 2 */
if(aNumber < 2) { return False; }
/* Even numbers. */
if (aNumber % 2 == 0) { return aNumber == 2; }
/* Odd numbers. */
/* Only need to check odd divisors as far as the square root. */
limit = (int)(sqrt(aNumber));
for (i = 3; i <= limit; i += 2)
{
if( aNumber % i == 0) { return False; }
}
/* Only prime numbers make it this far. */
return True;
}
Two is the only even prime, so all even numbers can be dealt with very quickly. Odd numbers only need to be tested with odd divisors less than or equal to the square root of the number: 9 = 3 * 3
There are faster methods, but they require construction of a table of primes. For your program, something like this appears to be sufficient.
Your code for checking a number is prime or not is not correct.
You should check the number never be divided any numbers less than the number.
Code of a function for checking a numer is prime or not is as follows:
/* function isPrime returns True if argument is prime number. */
boolean isPrime(int aNumber)
{
int i;
if(aNumber < 2) { return False; }
else if (aNumber==2) {return True;}
for i=2 to aNumber-1
{
if((aNumber%i) == 0){
return False;
}
}
return True;
}
I hope this give you some useful idea.
I have a question: I’m supposed to build a program where when I enter an integer below a hundred, all numbers smaller than said integer and containing the digit “3″ appear on the screen (etc, if I enter 14, the numbers “3, 13″ should appear).
However, there’s something wrong with my code, please help! Thank you!
The code:
#include <stdio.h>
int main(int argc, const char * argv [])
{
int wholenumber;
printf("百以内の整数を入力してください\n");
scanf_s("%d", &wholenumber);
while(0 <wholenumber)
{
wholenumber--;
while(0 < wholenumber){
wholenumber = 3 %10;
wholenumber = 3 /10;
if (wholenumber == 3);
{printf("%3d",wholenumber);}
}
}
return 0;
}
If x is an integer between 0 and 99, the following will check whether either of its digits is a 3:
if (x / 10 == 3 || x % 10 == 3) {
...
}
I leave the rest as an exercise for the reader.
I have no idea what your intention was with this code:
wholenumber = 3 % 10;
wholenumber = 3 / 10;
First line sets the variable to 3, the second to 0.. which forces the program to exit from the loop.
Code:
#include<stdio.h>
int main()
{
int i,num;
int t1,t2; // Variable to store data temporary
printf("\nEnter the number : \n");
scanf("%d",&num);
for(i=0;i<num;i++)
{
t1= i/10;
t2= i%10;
if((t1==3) || (t2 ==3)) //check if number has 3 in it
printf(" %d", i);
}
return 0;
}
This is code which is required.Thanks to #amulous for pointing out mistake.
Note: It is assumed that entered number is less than 100 as required by user who asked question.
#include <stdio.h>
int contain3(int n){
if(n == 0) return 0;
return (n % 10 == 3) ? 1 : contain3(n/10);
}
int main(void){
int i, wholenumber;
printf("百以内の整数を入力してください\n");
scanf_s("%d", &wholenumber);
for(i=3;i<wholenumber;++i)
if(contain3(i))
printf("%3d", i);
return 0;
}
#include <stdio.h>
#include <limits.h>
int main(void){
int i, wholenumber;
int data[]={3,13,23,30,31,32,33,34,35,36,37,38,39,43,53,63,73,83,93,INT_MAX};
printf("百以内の整数を入力してください\n");
scanf_s("%d", &wholenumber);
for(i=0;data[i]<wholenumber;++i)
printf("%3d", data[i]);
return 0;
}
OP solution is conceptionallly close but needs changes.
The while() loop test destroys wholenumber. The test for '3' containment should use a copy of wholenumber
the syntax of wholenumber = 3 /10; should be wholenumber_test /= 10;
other syntax errors.
void whole(int wholenumber, int digit) {
while (0 < wholenumber) {
int test = wholenumber; // form test value
while (0 < test) {
if ((test%10) == digit) {
printf("%3d\n", wholenumber);
break; // no need to test other digits
}
test /= 10; // move onto next digit
}
wholenumber--;
}
}
You can write this more efficiently, and this will work for any upper limit:
#include <stdio.h>
int main(int argc, const char * argv [])
{
int wholenumber;
printf("百以内の整数を入力してください\n");
scanf("%d", &wholenumber);
for (int tens = 1; tens < wholenumber; tens *= 10) {
for (int i = 3 * tens; i < wholenumber; i+= 10*tens) {
printf("%3d\n", i);
}
}
return 0;
}