I'm trying to make a program where the array size is not entered by the user,but the elements are, until 0 is entered.Now I want to check for each element which one is a perfect number,for that I have to do the sum of the divisors.Problem is I can't manage to do the sum of divisors for each element in the array,instead it adds all the divisors of all the elements in the array.
#include <stdio.h>
int main()
{
int n = 1000, i, j, sum = 0;
int v[n];
for (i = 1; i < n; i++)
{
scanf("%d", &v[i]);
if (v[i] == 0)
{
break;
}
for (j = 1; j < v[i]; j++)
{
if (v[i] % j == 0)
{
printf("%d", j);
sum = sum + j;
}
}
}
printf("\n%d",sum);
return 0;
}
OUTPUT
Brut force check can be very expensive. It is faster to build the table of perfect numbers using Euclides formula and then simple check if the number is perfect.
static unsigned long long getp(int x)
{
return (2ULL << (x - 2)) * ((2ULL << (x - 1)) - 1);
}
int isperfect(unsigned long long x)
{
const int primes[] = {2, 3, 5, 7, 13, 17, 19, 31};
static unsigned long long array[sizeof(primes) / sizeof(primes[0])];
int result = 0;
if(!array[0])
{
for(size_t index = 0; index < sizeof(primes) / sizeof(primes[0]); index++)
{
array[index] = getp(primes[index]);
}
}
for(size_t index = 0; index < sizeof(primes) / sizeof(primes[0]); index++)
{
if(x == array[index])
{
result = 1;
break;
}
}
return result;
}
The array of perfect numbers is build only one time on the first function call.
And some usage (your code a bit modified)
int main(void)
{
size_t n = 1000, i;
unsigned long long v[n];
for (i = 1; i < n; i++)
{
scanf("%llu", &v[i]);
if (v[i] == 0)
{
break;
}
printf("%llu is %s perfect number\n", v[i], isperfect(v[i]) ? "" : "not");
}
return 0;
}
https://godbolt.org/z/exMs345xb
Related
Write a function remove_digits that receives two arrays of type int. The first array contains a number of integers, and the second array is an array of digits. It is necessary to remove all digits from second array which are present in first array.
The function returns 1 if the ejection was successful.The function returns 1 if the eject was successful, and 0 if the array of digits is incorrect for some reason, if the array contains a value less than 0 or greater than 9, or if one of the members is repeated.
EXAMPLE 1:
int first[2]={12345, -12345},second[2]={3,5};
OUTPUT: 124 -124
EXAMPLE 2:
int first[5]={25, 235, 1235, 252, 22552255},second[3]={2,3,5};
OUTPUT: 0 0 1 0 0
My algorithm:
check if digit in second array is less than 0 or grater than 9 or digit is repeated, and in that case return 0 (finish program)
for negative numbers make them positive and in the end of first (for) loop make them negative
in the second (while) loop break number into digits, and for every number check if it's present in second array
if it is present, remove last digit
continue to the rest of elements
Code:
#include <stdio.h>
#include <stdlib.h>
int sum_of_digits(int n) {
int i, sum = 0;
while (n > 0) {
sum++;
n /= 10;
}
return sum;
}
int divide(int n) {
int num_of_digits = sum_of_digits(n);
switch (num_of_digits) {
case 1:
break;
case 2:
break;
case 3:
n /= 10;
break;
case 4:
n /= 100;
break;
case 5:
n /= 1000;
break;
case 6:
n /= 1000;
break;
case 7:
n /= 10000;
break;
case 8:
n /= 100000;
break;
case 9:
n /= 1000000;
default:
break;
}
return n;
}
int remove_digits(int *first, int n, int *second, int vel) {
// first - removing digits from second
// second - searching for digits
int i, j, num, digit, neg = 0;
for (i = 0; i < vel; i++) {
// invalid digit
if (second[i] < 0 || second[i] > 9)
return 0;
for (j = i + 1; j < vel; j++)
// repeated digit
if (second[j] == second[i])
return 0;
}
for (i = 0; i < n; i++) {
// negative case
if (first[i] < 0) {
first[i] = abs(first[i]);
neg = 1;
}
num = first[i];
while (num > 0) {
digit = num % 10;
for (j = 0; j < vel; j++)
if (second[j] == digit)
// remove last digit
first[i] = divide(first[i]) - digit;
num /= 10;
}
if (first[i] <= 0)
first[i] = 0;
if (neg == 1)
first[i] *= -1;
}
return 1;
}
int main() {
int first[2] = {12345, 12345}, second[2] = {3, 5}, i;
remove_digits(first, 2, second, 2);
for (i = 0; i < 2; i++)
printf("%d ", first[i]);
return 0;
}
MY OUTPUT: 4 4
Could you help me to modify my algorithm to work correctly?
simplified approach for your problem would be as follows,
#include <stdio.h>
#include <stdlib.h>
int removeDigit(int src, int digit){
int neg = (src < 0)?-1:1;
int num = abs(src);
src = 0;
//remove digit
while(num){
int num_digit = num%10;
if(num_digit != digit){
src = src * 10 + num_digit;
}
num /= 10;
}
//reverse number
while(src){
num = num * 10 + src%10;
src /=10;
}
return num*neg;
}
int remove_digits(int *first, int n, int *second, int m) {
// first - removing digits from second
// second - searching for digits
int i, j;
for (i = 0; i < m; i++) {
// invalid digit
if (second[i] < 0 || second[i] > 9)
return 0;
for (j = i + 1; j < m; j++)
// repeated digit
if (second[j] == second[i])
return 0;
}
for (i = 0; i < n; ++i) {
for(j =0; j<m; ++j){
first[i]= removeDigit(first[i],second[j]);
}
}
return 1;
}
int main() {
{
printf("Test 1\n");
int first[] = {12345, 12345}, second[] = {3, 5}, i;
remove_digits(first, sizeof(first)/sizeof(first[0]), second, sizeof(second)/sizeof(second[0]));
for (i = 0; i < sizeof(first)/sizeof(first[0]); i++)
printf("%d ", first[i]);
}
{
printf("\n\nTest 2\n");
int first[] = {25, 235, 1235, 252, 22552255}, second[] = {2,3,5}, i;
remove_digits(first, sizeof(first)/sizeof(first[0]), second, sizeof(second)/sizeof(second[0]));
for (i = 0; i < sizeof(first)/sizeof(first[0]); i++)
printf("%d ", first[i]);
}
return 0;
}
I'm trying to write a program that will sort an array of 20 random numbers by the sums of their digits.
For example:
"5 > 11" because 5 > 1+1 (5 > 2).
I managed to sort the sums but is it possible to return to the original numbers or do it other way?
#include <stdio.h>
void sortujTab(int tab[], int size){
int sum,i;
for(int i=0;i<size;i++)
{
while(tab[i]>0){//sum as added digits of an integer
int p=tab[i]%10;
sum=sum+p;
tab[i]/=10;
}
tab[i]=sum;
sum=0;
}
for(int i=0;i<size;i++)//print of unsorted sums
{
printf("%d,",tab[i]);
}
printf("\n");
for(int i=0;i<size;i++)//sorting sums
for(int j=i+1;j<=size;j++)
{
if(tab[i]>tab[j]){
int temp=tab[j];
tab[j]=tab[i];
tab[i]=temp;
}
}
for(int i=0;i<20;i++)//print of sorted sums
{
printf("%d,",tab[i]);
}
}
int main()
{
int tab[20];
int size=sizeof(tab)/sizeof(*tab);
for(int i=0;i<=20;i++)
{
tab[i]=rand()%1000;// assamble the value
}
for(int i=0;i<20;i++)
{
printf("%d,",tab[i]);//print unsorted
}
printf("\n");
sortujTab(tab,size);
return 0;
}
There are two basic approach :
Create a function that return the sum for an integer, say sum(int a), then call it on comparison, so instead of tab[i] > tab [j] it becomes sum(tab[i]) > sum (tab[j])
Store the sum into a different array, compare with the new array, and on swapping, swap both the original and the new array
The first solution works well enough if the array is small and takes no extra memory, while the second solution didn't need to repeatedly calculate the sum. A caching approach is also possible with map but it's only worth it if there are enough identical numbers in the array.
Since your numbers are non-negative and less than 1000, you can encode the sum of the digits in the numbers itself. So, this formula will be true: encoded_number = original_number + 1000 * sum_of_the_digits. encoded_number/1000 will decode the sum of the digits, and encoded_number%1000 will decode the original number. Follow the modified code below. The numbers enclosed by parentheses in the output are original numbers. I've tried to modify minimally your code.
#include <stdio.h>
#include <stdlib.h>
void sortujTab(int tab[], int size)
{
for (int i = 0; i < size; i++) {
int sum = 0, n = tab[i];
while (n > 0) { //sum as added digits of an integer
int p = n % 10;
sum = sum + p;
n /= 10;
}
tab[i] += sum * 1000;
}
for (int i = 0; i < size; i++) { //print of unsorted sums
printf("%d%c", tab[i] / 1000, i < size - 1 ? ',' : '\n');
}
for (int i = 0; i < size; i++) { //sorting sums
for (int j = i + 1; j < size; j++) {
if (tab[i] / 1000 > tab[j] / 1000) {
int temp = tab[j];
tab[j] = tab[i];
tab[i] = temp;
}
}
}
for (int i = 0; i < size; i++) { //print of sorted sums
printf("%d(%d)%c", tab[i] / 1000, tab[i] % 1000, i < size - 1 ? ',' : '\n');
}
}
int main(void)
{
int tab[20];
int size = sizeof(tab) / sizeof(*tab);
for (int i = 0; i < size; i++) {
tab[i] = rand() % 1000; // assamble the value
}
for (int i = 0; i < size; i++) {
printf("%d%c", tab[i], i < size - 1 ? ',' : '\n'); //print unsorted
}
sortujTab(tab, size);
return 0;
}
If the range of numbers doesn't allow such an encoding, then you can declare a structure with two integer elements (one for the original number and one for the sum of its digits), allocate an array for size elements of this structure, and initialize and sort the array using the digit sums as the keys.
You can sort an array of indexes rather than the array with data.
#include <stdio.h>
//poor man's interpretation of sumofdigits() :-)
int sod(int n) {
switch (n) {
default: return 0;
case 5: return 5;
case 11: return 2;
case 1000: return 1;
case 9: return 9;
}
}
void sortbyindex(int *data, int *ndx, int size) {
//setup default indexes
for (int k = 0; k < size; k++) ndx[k] = k;
//sort the indexes
for (int lo = 0; lo < size; lo++) {
for (int hi = lo + 1; hi < size; hi++) {
if (sod(data[ndx[lo]]) > sod(data[ndx[hi]])) {
//swap indexes
int tmp = ndx[lo];
ndx[lo] = ndx[hi];
ndx[hi] = tmp;
}
}
}
}
int main(void) {
int data[4] = {5, 11, 1000, 9};
int ndx[sizeof data / sizeof *data];
sortbyindex(data, ndx, 4);
for (int k = 0; k < sizeof data / sizeof *data; k++) {
printf("%d\n", data[ndx[k]]);
}
return 0;
}
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.
#include <stdio.h>
#include <math.h>
int prime (long n);
long reverse(long n);
int main(void)
{
long n;
long i, j;
puts("Enter n dight number, and we will help you find symmetrical prime number");
scanf("%ld", &n);
for (i = 11; i < (pow(10, n) - 1); i+= 2)
{
if (prime(i))
{
j = reverse(i);
if (i == j)
{
printf("%ld\n", i);
}
}
}
}
int prime (long n) //estimate whether the number n is primer number
{
int status = 0;
int j;
//1 is prime, 0 is not
if (n % 2 == 0 || n == 3)
{
if (n == 2)
status = 1;
if (n == 3)
status = 1;
else
{
n++;
status = 0;
}
}
else
{
j = 3;
while (j <= sqrt(n))
{
if (n % j == 0)
{
status = 0;
break;
}
else
status = 1;
j+= 2;
}
}
return status;
}
long reverse(long n) //reverse a number
{
int i, j, x;
long k, sum;
int digit = 0;
int ar[1000];
while (n > 0)
{
k = n;
n = n / 10;
x = (k - n*10);
digit++;
ar[digit] = x;
}
for (i = 1,j = digit - 1; i <= digit; i++, j--)
{
sum += ar[i] * pow(10, j)
}
return sum;
}
I build a reverse function in order to reverse numbers, for example, 214, to 412.
This function works fine in individual number, for instance, I type reverse(214), it return 412, which is good. But when I combine reverse() function with for loop, this function can not work... it produces some strange number...
so How can I fix this problem?
The reverse function is extremely complicated. The better way to go about it would be:
long reverse (long n)
{
long result = 0;
while (n != 0)
{
result *= 10;
result += n % 10;
n /= 10;
}
return result;
}
I think the problem in your code is that in the following segment
digit++;
ar[digit] = x;
you first increment the position then assign to it, thus leaving ar[0] unintialized.
How can I fix this problem?
You need to initialize sum
long k, sum = 0;
^
See the code from #Armen Tsirunyan for a simpler approach.
I am trying to implement the sieve of eratosthenes in C. The code works for small input values, but once the input goes beyond a certain range, a run- time error is thrown. This is the second problem in the classical section of the SPOJ base. What is the mistake?
#include<stdio.h>
#include<math.h>
int prime(unsigned long int, unsigned long int);
int main()
{
int nitem;
unsigned long int sn,fn;
scanf("%d", &nitem);
while(nitem)
{
scanf("%lu", &fn);
//printf("%d",fn);
scanf("%lu", &sn);
prime(fn, sn);
nitem--;
}
return 0;
}
int prime(unsigned long int fn, unsigned long int sn)
{
unsigned long int prim[100000];
int i,j,k;
for(i = 0; i < 100000; i++)
{
prim[i] = 1;
}
prim[0] = 0;
prim[1] = 0;
//printf("%d", sn);
//printf("%d", k);
//printf("%d", (k <= sn));
for(k = 2; k <= sqrt(sn); k++)
{
// printf("alksnc%5d", k);
if(prim[k] == 1)
{
for(j = 2; (k * j) <= sn; j++)
{
//printf("%d", prim[k]);
prim[k * j] = 0;
}
}
}
for(int i = 0; i <= sn; i++)
{
if(prim[i] !=0 && i >= fn)
{
printf("%lu\n", i);
}
}
printf("\n");
return;
}
Input:
1
100000 100345
output:
run time error
Input:
1
3 5
output:
3
5
We can make more efficient use of memory (2x) by only sieving odd numbers as all the even numbers you're processing waste time and space. It's trickier to work out but gives us something like:
#include <math.h>
#include <libc.h>
#define MAX_ODD_PRIMES 1048576
void prime(unsigned long fn, unsigned long sn)
{
unsigned char primes[MAX_ODD_PRIMES];
for (unsigned long i = 0; i < MAX_ODD_PRIMES; i++)
{
primes[i] = TRUE;
}
primes[0] = 0; // preset first odd, '1'
for (unsigned long k = 3; k <= sqrt(sn) + 1; k += 2)
{
if (primes[k / 2])
{
for (unsigned long j = 3; (k * j) <= sn; j += 2)
{
primes[k * j / 2] = FALSE;
}
}
}
if (fn <= 2)
{
printf("2\n");
fn = 3;
}
for (unsigned long i = fn / 2; i * 2 + 1 <= sn; i++)
{
if (primes[i])
{
printf("%lu\n", i * 2 + 1);
}
}
}
EXAMPLE
> ./a.out
1 1999900 2000000
1999957
1999969
1999979
1999993
>
1) Array range error.
By changing code
for (j = 2; (k * j) <= sn; j++) {
if (k * j >= 100000) {
printf("Out of range %d %d\n", k, j);
exit(1);
}
prim[k * j] = 0;
}
}
With input 2, 100000
Output
Out of range 2 50000
By using an array (VLA) sized to the task, this is avoided. Many other optimizations available. Consider also a malloc() array.
void prime(unsigned long int fn, unsigned long int sn) {
unsigned long int prim[sn + 1];
2) int prime() eventually performs return; where return something; is expected. Suggest changing function to void prime()
int prime(unsigned long int fn, unsigned long int sn) {
unsigned long int prim[100000];
...
printf("\n");
return;
}