Prime printing. Ask for point out errors in the code - c

Put all the prime numbers of lim in the aa array.
This function returns the number of the obtained prime numbers, and finally prints these prime numbers.
Here is my code.
#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<string.h>
#define MAX 100
int func(int lim,int aa[MAX])
{
int i,count,num;
num = 0;
for(count = 2;count<lim;count++)
{
for(i=2;i<=sqrt(count);i++)
{
if(count%i==0)
break;
}
if(i>sqrt(count))
{
aa[num]=i;
num++;
}
}
return num;
}
int main()
{
int limit,i,sum;
int aa[MAX];
printf("Please input an integer:");
scanf("%d",&limit);
sum=func(limit,aa);
for(i=0;i<sum;i++)
{
if(i%10==0&&i!=0)
printf("\n");
printf("%5d",aa[i]);
}
return 0;
}
Unfortunately, the results I got when I ran the program did not meet the expectations.
The error is that every run results have a 2 in the first place and loss the last number
e.g.
And it should be 2 3 5.

Avoid floating point math for an integer problem
Do not use sqrt().
// for(i=2;i<=sqrt(count);i++)
for(i = 2; i <= count/i; i++)
Do not iterate once MAX values found
aa[num]=i;
num++;
if (num == MAX) return num; //add
I'd recommend an isprime() helper function to simplify code.
int isprime(int num) {
if (num % 2 == 0)
return num == 2;
for (int divisor = 3; divisor <= num / divisor; divisor += 2) {
if (num % divisor == 0)
return 0;
}
return num > 1;
}
int func(int lim, int aa[MAX]) {
size_t prime_index = 0;
for(int prime_candidate = 2; prime_candidate <= lim; prime_candidate++) {
if (isprime(prime_candidate)) {
aa[num] = prime_candidate;
num++;
if (num == MAX) break;
}
}
return num;
}

Related

Print Prime Numbers and Reversed Number

A number and a reversed number form a pair. If both numbers are prime numbers, we call it a reversed prime number pair. For instance, 13 and 31 is a 2 digit reversed prime number pair, 107 and 701 is a 3 digit reversed prime number pairs.
Write a program to output all n (2<=n<=5) digit reversed prime number pairs. If the input is less than 2 or greater than 5, output "Wrong input." and terminate the program. While ouputting , every 5 pairs form a new line, and only output the pair in which the first number is smaller than the second number.
Input: 1
Output: Wrong input.
Input: 3
Output:
(107,701)(113,311)(149,941)(157,751)(167,761)
(179,971)(199,991)(337,733)(347,743)(359,953)
(389,983)(709,907)(739,937)(769,967)
There are 14 results.
Can anyone give me hints how to do this?
I know how to determine if a number is a reversed prime number, but i couldn't understand how to complete this challenge from my friend
#include <stdio.h>
int checkPrime(int n) {
int i, isPrime = 1;
if (n == 0 || n == 1) {
isPrime = 0;
}
else {
for(i = 2; i <= n/2; ++i) {
if(n % i == 0) {
isPrime = 0;
break;
}
}
}
return isPrime;
}
int main (void)
{
int a, reverse = 0, remainder, flag=0;
scanf("%d",&a);
int temp = a;
while (temp!=0) {
remainder = temp%10;
reverse = reverse*10 + remainder;
temp/=10;
}
if (checkPrime(a)==1) {
if (checkPrime(reverse)==1){
printf("YES\n");
flag=1;
}
}
if (flag==0)
printf("NO\n");
}
This will be the correct solution:
#include <stdio.h>
#include <stdbool.h>
#include <math.h>
#include <stdlib.h>
#define MAX_N 100000
int *primes;
int num_primes;
void init_primes() {
int sqrt_max_n = sqrt(MAX_N);
primes = (int *) malloc(sqrt_max_n / 2 * sizeof(int));
num_primes = 0;
primes[num_primes] = 2;
num_primes++;
for (int i = 3; i <= sqrt_max_n; i += 2) {
bool is_prime = true;
for (int j = 0; j < num_primes; j++) {
if (i % primes[j] == 0) {
is_prime = false;
break;
}
}
if (is_prime) {
primes[num_primes] = i;
num_primes++;
}
}
}
int is_prime(int n) {
for (int i = 0; i < num_primes; i++) {
if (primes[i] == n) {
return 1;
}
if (n % primes[i] == 0) {
return 0;
}
}
return 1;
}
int reverse(int n) {
int reversed_n = 0;
while (n > 0) {
reversed_n = reversed_n * 10 + n % 10;
n /= 10;
}
return reversed_n;
}
int main() {
init_primes();
int n;
printf("Enter n (2 <= n <= 5): ");
scanf("%d", &n);
if (n < 2 || n > 5) {
printf("Wrong input.\n");
return 0;
}
int min = (int) pow(10, n - 1);
int max = (int) pow(10, n) - 1;
int count = 0;
for (int i = min; i <= max; i++) {
if (is_prime(i)) {
int reversed_i = reverse(i);
if (i < reversed_i && is_prime(reversed_i)) {
printf("(%d %d)", i, reversed_i);
count++;
if (count % 5 == 0) {
printf("\n");
} else {
printf(" ");
}
}
}
}
return 0;
}
After testing this code I get the same result what you need:
Enter n (2 <= n <= 5): 3
(107 701) (113 311) (149 941) (157 751) (167 761)
(179 971) (199 991) (337 733) (347 743) (359 953)
(389 983) (709 907) (739 937) (769 967)
The init_primes method caches all the required prime numbers until the sqrt of your limit to a dynamic array.
The is_prime method uses that cache for detecting whether a number is prime or not.

A code made to tell if a number is "Perfect Number"

This is a code I wrote in C to find if a given number is a Perfect number or Not.
A Perfect number is a number that is the sum of all its factors.
EXAMPLE - 6
6 has factors 2 , 3 and 1 (1 because it divisible by itself)
and 2 + 3 + 1 = 6
#include <stdio.h>
int main(){
int number;
int sum =0,i;
scanf("%d",&number);
for(i=0;i<number;i++){
if(number % i==0){
sum += i;
}else{ sum = sum;}
}if(sum==number){
printf("Perfect Number");
}else{
printf("Not a Perfect Number");
}
return 0;
}
The code is logically correct and its suppose to give the right output but the problem is that it is not giving any output.
Instead in CLion it terminates with a code " Process finished with exit code -1073741676 (0xC0000094)"
Your loop must have i to start from 1, not 0, otherwise you'll have division by zero when you do number % i == 0:
#include <stdio.h>
int main(void) {
int number;
int sum = 0;
printf("Insert number: ");
scanf("%d", &number);
// NOTE: replaced condition `i < number` with `i <= number / 2`
// for improved performance
for (int i = 1; i <= number / 2; i++) {
if (number % i == 0) {
sum += i;
}
}
if (sum == number) {
printf("Perfect Number\n");
}
else {
printf("Not a Perfect Number\n");
}
return 0;
}
Here is a solution with Cyclomatic Complexity of 2. I don't see a reason for this, but you can do it.
#include <stdio.h>
int main(void)
{
int number = 33550336;
int sum = 0;
for(int i = 1; i <= number / 2; i++) {
sum += i * (number % i == 0);
}
printf("%d is %s", number, "not a perfect number." + 4 * (sum==number));
return 0;
}
Function version:
#include <stdio.h>
#include <stdbool.h>
bool is_perfect(int number)
{
int sum = 0;
for(int i = 1; i <= number / 2; i++) {
sum += i * (number % i == 0);
}
return sum == number;
}
int main(void)
{
int n = 33550336;
printf("%d is %s", n, "not a perfect number." + 4 * is_perfect(n));
return 0;
}
The best version is this one with Cyclomatic Complexity of 1:
bool is_perfect(int n)
{
return n == 6 || n == 28 || n == 496 || n == 8128 || n == 33550336;
}
Much faster! 😅

How to find the nth number?

For an assignment, I have to write code which accepts as input an integer n and outputs the nth 'superunusual' number.
The first few su-numbers are: 22, 23, 26, 33, ... So when the input is 1, the output should be 22. 2 gives 23 and 3 gives 26.
I already have a code that checks if the input number is a su-number, but I can't find a way to calculate the nth number.
So when I now input 22, it says that 22 is a superunusual number.
The code:
/* calculates largest prime factor */
int lprime(int n) {
int max = -1;
while (n % 2 == 0) {
max = 2;
n /= 2;
}
for (int i = 3; i*i <= n; i += 2) {
while (n % i == 0) {
max = i;
n = n / i;
}
}
if (n > 2) {
max = n;
}
return max;
}
/* check unusual number */
int unus(int n) {
/* find largest prime of number */
int factor = lprime(n);
/* Check if largest prime > sqrt(n) */
if ((factor*factor) > n) {
return 1; /* true */
}
else {
return 0; /* false */
}
}
/* delete digit from number */
int del(int num, int n) {
int d = log10(num)+1; /* checks amount of digits */
int revnew = 0;
int new = 0;
for (int i = 0; num != 0; i++) {
int dig = num % 10;
num = num / 10;
if(i == (d - n)) {
continue;
} else {
revnew = (revnew * 10) + dig;
}
}
for (int i = 0; revnew != 0; i++) {
new = (new*10) + (revnew % 10);
revnew = revnew / 10;
}
return new;
}
/* driver code */
int main(int argc, char* v[]) {
int m=22, n;
int x = 0;
int i = 1;
int counter = 0;
scanf("%d", &n);
int d = log10(m)+1;
while (counter < n) {
if (unus(m++)) {
counter++;
}
}
for(unus(m); i < d; i++) {
int nmin = del(m, i);
if (unus(nmin)) {
continue;
} else {
printf("%d is not supurunusual\n", (m-1));
x++;
}
}
if(x==0) {
printf("%d is superunusual!\n", (m-1));
}
return 0;
}
I hope you can understand my code. Otherwise I will explain it better.
Also, I'm quite new to coding, so please don't be to harsh...
You have a function to determine whether a number is unusual, but you do the check whether a number is super-unusual in the body of the main routine. If you extract that code into a proper function:
int is_superunusual(int m)
{
int d = log10(m) + 1;
if (unus(m) == 0) return 0;
for(int i = 0; i < d; i++) { // see footnote
int nmin = del(m, i);
if (unus(nmin) == 0) return 0;
}
return 1;
}
then you can use Eugene's code:
while (counter < n) {
if (is_superunusual(m++)) {
counter++;
}
}
printf("The su number #%d is %d\n", n, m - 1);
Your code tested for unusual numbers, not super-unusual numbers.
Footnote: If you take del(num, n) to mean "remove the nth digit from the end", you can do away with the log10 call in del. You must check all deletions anyway, so the order doesn't really matter here.

Finding the numbers that are palindromic in both base 2 and 10 and summing them up

I need to find the sum of all numbers that are less or equal with my input number (it requires them to be palindromic in both radix 10 and 2). Here is my code:
#include <stdio.h>
#include <stdlib.h>
int pal10(int n) {
int reverse, x;
x = n;
while (n != 0) {
reverse = reverse * 10 + n % 10;
n = n / 10;
}
if (reverse == x)
return 1;
else
return 0;
}
int length(int n) {
int l = 0;
while (n != 0) {
n = n / 2;
l++;
}
return l;
}
int binarypal(int n) {
int v[length(n)], i = 0, j = length(n);
while (n != 0) {
v[i] = n % 2;
n = n / 2;
i++;
}
for (i = 0; i <= length(n); i++) {
if (v[i] == v[j]) {
j--;
} else {
break;
return 0;
}
}
return 1;
}
int main() {
long s = 0;
int n;
printf("Input your number \n");
scanf("%d", &n);
while (n != 0) {
if (binarypal(n) == 1 && pal10(n) == 1)
s = s + n;
n--;
}
printf("Your sum is %ld", s);
return 0;
}
It always returns 0. My guess is I've done something wrong in the binarypal function. What should I do?
You have multiple problems:
function pal10() fails because reverse is not initialized.
function binarypal() is too complicated, you should use the same method as pal10().
you should avoid comparing boolean function return values with 1, the convention in C is to return 0 for false and non zero for true.
you should avoid using l for a variable name as it looks very similar to 1 on most constant width fonts. As a matter of fact, it is the same glyph for the original Courier typewriter font.
Here is a simplified and corrected version with a multi-base function:
#include <stdio.h>
#include <stdlib.h>
int ispal(int n, int base) {
int reverse = 0, x = n;
while (n > 0) {
reverse = reverse * base + n % base;
n = n / base;
}
return reverse == x;
}
int main(void) {
long s = 0;
int n = 0;
printf("Input your number:\n");
scanf("%d", &n);
while (n > 0) {
if (ispal(n, 10) && ispal(n, 2))
s += n;
n--;
}
printf("Your sum is %ld\n", s);
return 0;
}
in the function pal10 the variable reverse is not initialized.
int pal10(int n)
{
int reverse,x;
^^^^^^^
x=n;
while(n!=0)
{
reverse=reverse*10+n%10;
n=n/10;
}
if(reverse==x)
return 1;
else
return 0;
}
In the function binarypal this loop is incorrect because the valid range of indices of an array with length( n ) elements is [0, length( n ) - 1 ]
for(i=0;i<=length(n);i++)
{
if(v[i]==v[j])
{
j--;
}
else
{
break;
return 0;
}
}
And as #BLUEPIXY pointed out you shall remove the break statement from this else
else
{
break;
return 0;
}

How to find the sum of Prime Numbers in C within a given range?

I'm very new to programming and I was asked to find the sum of prime numbers in a given range, using a while loop. If The input is 5, the answer should be 28 (2+3+5+7+11). I tried writing the code but it seems that the logic isn't right.
CODE
#include <stdio.h>
int main()
{
int range,test;
int sum = 2;
int n = 3;
printf("Enter the range.");
scanf("%i",range);
while (range > 0)
{
int i =2;
while(i<n)
{
test = n%i;
if (test==0)
{
goto end;
}
i++;
}
if (test != 0)
{
sum = sum + test;
range--;
}
end:
n++;
}
printf("The sum is %i",sum);
return 0;
}
It would be nice if you could point out my mistake and possibly tell me how to go about from there.
first of all, in the scanf use &range and not range
scanf("%i",&range);
Second this instruction is not correct
sum = sum + test;
it should be
sum = sum + n;
and also the
while (range > 0)
should be changed to
while (range > 1)
Because in your algorithm you have already put the first element of the range in the sum sum = 2 so the while should loop range - 1 times and not range times
That's all
OK, my C is really bad, but try something like the following code. Probably doesn't compile, but if it's a homework or something, you better figure it out yourself:
UPDATE: Made it a while loop as requested.
#include <stdio.h>
int main()
{
int range, test, counter, innerCounter, sum = 1;
int countPrimes = 1;
int [50] primesArray;
primesArray[0] = 1;
printf("Enter the range.");
scanf("%i",range);
counter = 2;
while (counter <= range) {
for (innerCounter = 1; innerCounter < countPrimes; innerCounter++) {
if (counter % primesArray[innerCounter] == 0)
continue;
primesArray[countPrimes + 1] = counter;
countPrimes ++;
sum += counter;
}
counter ++
}
printf("The sum is %i",sum);
return 0;
}
I haven't done C in a while, but I'd make a few functions to simplify your logic:
#include <stdio.h>
#include <math.h>
int is_prime(n) {
int i;
for (i = 2; i <= sqrt(n); i++) {
if (n % i == 0) {
return 0;
}
}
return 1;
}
int main() {
int range, i, sum, num_primes = 0;
printf("Enter the range: ");
scanf("%d", &range);
for (i = 2; num_primes < range; i++) {
if (is_prime(i)) {
sum += i;
num_primes++;
}
}
printf("The sum is %d", sum);
return 0;
}
Using goto and shoving all of your code into main() will make your program hard to debug.
Copy - pasted from here.
#include <stdio.h>
int main() {
int i, n, count = 0, value = 2, flag = 1, total = 0;
/* get the input value n from the user */
printf("Enter the value for n:");
scanf("%d", &n);
/* calculate the sum of first n prime nos */
while (count < n) {
for (i = 2; i <= value - 1; i++) {
if (value % i == 0) {
flag = 0;
break;
}
}
if (flag) {
total = total + value;
count++;
}
value++;
flag = 1;
}
/* print the sum of first n prime numbers */
printf("Sum of first %d prime numbers is %d\n", n, total);
return 0;
}
Output:
Enter the value for n:5
Sum of first 5 prime numbers is 28
Try the simplest approach over here. Check C program to find sum of all prime between 1 and n numbers.
CODE
#include <stdio.h>
int main()
{
int i, j, n, isPrime, sum=0;
/*
* Reads a number from user
*/
printf("Find sum of all prime between 1 to : ");
scanf("%d", &n);
/*
* Finds all prime numbers between 1 to n
*/
for(i=2; i<=n; i++)
{
/*
* Checks if the current number i is Prime or not
*/
isPrime = 1;
for(j=2; j<=i/2 ;j++)
{
if(i%j==0)
{
isPrime = 0;
break;
}
}
/*
* If i is Prime then add to sum
*/
if(isPrime==1)
{
sum += i;
}
}
printf("Sum of all prime numbers between 1 to %d = %d", n, sum);
return 0;
}

Resources