I am having issues with a task I've done, it outputs answer correctly without any errors. It gives me 2/3 points, last shows error, and doesn't show what. I've no clue what I've done wrong. Can someone have a look at this please.
Task:
A perfect number is a natural number that is equal to the sum of all its natural divisors (different from itself).
6 = 1 + 2 + 3
28 = 1 + 2 + 4 + 7 + 14
A redundant number is a natural number which is greater than the sum of all its natural divisors (different from itself).
9> 1 + 3
The deficit number is a natural number that is less than the sum of all its natural divisors (different from itself).
12 <1 + 2 + 3 + 4 + 6
Input
A natural number N (N <1000) followed by N natural numbers (not greater than 32000).
Remember 0 is an natural number.
For each of the numbers given in the input, the program should print a line of the form on the screen:
X - perfect / redundant / deficit number
depending on the type of number.
Sample input
6 15 28 6 56 22 496
Sample output
15 - redundant number
28 - perfect number
6 - perfect number
56 - deficit number
22 - redundant number
496 - a perfect number
#include <iostream>
using namespace std;
void ifPerfect(int n)
{
int sum = 0;
for (int i = 1; i <= n / 2; i++)
if (n % i == 0)
sum += i;
if (sum == n)
{
cout << n << " - perfect number" << endl;
}
}
void ifRedundant(int n)
{
int sum = 0;
for (int i = 1; i < n; i++)
{
if (n % i == 0)
{
sum += i;
}
}
if (n > sum)
{
cout << n << " - redundant number" << endl;
}
}
void ifDeficit(int n)
{
int sum = 0;
for (int i = 1; i < n; i++)
{
if (n % i == 0)
{
sum += i;
}
}
if (n < sum)
{
cout << n << " - deficit number" << endl;
}
}
int main()
{
int n;
cin >> n;
if (n >= 0 && n < 1000)
{
int *tab = new int[n];
for (int i = 0; i < n; i++)
{
cin >> tab[i];
}
for (int i = 0; i < n; i++)
{
ifRedundant(tab[i]);
ifPerfect(tab[i]);
ifDeficit(tab[i]);
}
delete[] tab;
return 0;
}
}
According to Wiki (https://en.wikipedia.org/wiki/Perfect_number), 0 is NOT a perfect number, while your program would say that it is.
Given an input of 0, you program will produce an incorrect answer.
The clue was the statement "Remember 0 is an natural number."
While natural, it is not perfect.
Related
I'm coding on a leetcode-like platform. There is a task: counter the number of primes below a given bound.
I used the algorithm: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
I copy the code from here: https://www.geeksforgeeks.org/sieve-of-eratosthenes/ , except that I make false represents isPrime to avoid using memset. Here is my code:
void SieveOfEratosthenes(int n)
{
bool *prime = new bool[n+1](); // initialized by false by default
for (int p=2; p*p<=n; p++)
{
if (prime[p] == false)
{
for (int i=p*p; i<=n; i += p)
prime[i] = true;
}
}
for (int p=2; p<=n; p++)
if (prime[p])
cout << p << " ";
}
However, when I execute it, the platform tells me that I used too much memory in the case of 100 000 000 as the enter.
I've checked that sizeof(bool) equals to 1.
Is there some way to use less memory for this piece of code?
A couple of suggestions:
use a bit array representing only odd numbers
break the problem up into segments so the partial sieve uses much less memory
#Kim Walish has a fast C++ version here:
https://github.com/kimwalisch/primesieve/wiki/Segmented-sieve-of-Eratosthenes
You can make it use less memory still by always limiting the segment size to the L1 cache size, and by changing the IsPrime array to also be a bit array of odd numbers.
This is a memory optimized implementation of the sieve of eratosthenes. The basic idea is that, you only need to store the status of the odd numbers. Rest of it is similar to the normal implementation.
#include <iostream>
class Solution {
public:
int countPrimes(int n) {
//if(n <= 1) return 0; // including n
if(n <= 2) return 0; // number of primes less than 0 / 1 / 2 is 0
const int MAXN = 1500000 + 5; // adjust MAXN accordingly
// finding prime from 1 up to N
int status[(MAXN >> 1) + 1]; // we need space for only the odd numbers
// works well up to 1.5 * 10 ^ 6, for numbers larger than that, you need to adjust the second operand accordingly
int prime[115000 + 1000]; // prime number distribution , pi(x) = x/ (ln(x) - 1) , adjust this according to MAXN
// If status[i] = 0 -> i is prime
// If status[i] = 1 -> i is not prime
for(int i = 1 ; i <= (n >> 1) ; ++i) status[i] = 0; // for every i , 2 * i + 1 is the odd number, marking it as prime
int sqrtN = static_cast <int> ((sqrt (static_cast <double> (n))));
// computing sqrt(N) only once because it is costly computing it inside a loop
// only accounting the odd numbers and their multiples
for(int i = 3 ; i <= sqrtN ; i += 2){
if(status[i >> 1] == 0){
// if this is still a prime then discard its multiples
// first multiple that needs to be discarded starts at i * i
// all the previous ones have already been discarded
for(int j = i * i ; j <= n ; j += (i + i)) {
//printf("Marking %d as not prime\n",j);
status[j >> 1] = 1;
}
}
}
int counter = 0;
prime[counter++] = 2;
for(int i = 3 ; i <= n ; i += 2){
if(status[i >> 1] == 0){
prime[counter++] = i;
}
}
if( (n & 1) && !status[n >> 1]) counter--; // if n is prime, discard n
std::cout << "Number of primes less than " << n << " is " << counter << "\n";
for(int i = 0 ; i < counter; ++i){
std::cout << prime[i];
if(i != counter - 1) std::cout << "\n";
}
std::cout << "\n";
return counter;
}
};
int main(int argc, char const *argv[])
{
Solution solution;
int n; std::cin >> n;
solution.countPrimes(n);
return 0;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Given N three-digit numbers, your task is to find bit score of all N numbers and then print the number of pairs possible based on these calculated bit score.
Rule for calculating bit score from three digit number:
From the 3-digit number,
· extract largest digit and multiply by 11 then
· extract smallest digit multiply by 7 then
· add both the result for getting bit pairs.
Note: - Bit score should be of 2-digits, if above results in a 3-digit bit score, simply ignore most significant digit.
Consider following examples:
Say, number is 286
Largest digit is 8 and smallest digit is 2
So, 8*11+2*7 =102 so ignore most significant bit , So bit score = 02.
Say, Number is 123
Largest digit is 3 and smallest digit is 1
So, 3*11+7*1=40, so bit score is 40.
Rules for making pairs from above calculated bit scores
Condition for making pairs are
· Both bit scores should be in either odd position or even position to be eligible to form a pair.
· Pairs can be only made if most significant digit are same and at most two pair can be made for a given significant digit.
Constraints
N<=500
Input Format
First line contains an integer N, denoting the count of numbers.
Second line contains N 3-digit integers delimited by space
Output
One integer value denoting the number of bit pairs.
Test Case
Explanation
Example 1
Input
8 234 567 321 345 123 110 767 111
Output
3
Explanation
After getting the most and least significant digits of the numbers and applying the formula given in Rule 1 we get the bit scores of the numbers as:
58 12 40 76 40 11 19 18
No. of pair possible are 3:
40 appears twice at odd-indices 3 and 5 respectively. Hence, this is one pair.
12, 11, 18 are at even-indices. Hence, two pairs are possible from these three-bit scores.
Hence total pairs possible is 3
#include <iostream>
#include <vector>
using namespace std;
vector<int> correctBitScores(vector<int>);
vector<int> bitScore(vector<int>);
int findPairs(vector<int>);
int main() {
int a, b;
int pairs = 0;
vector<int> vec;
vector<int> bitscore;
cout << "\nEnter count of nos: ";
cin >> a;
for (int i = 0; i < a; i++) {
cin >> b;
vec.push_back(b);
}
bitscore = bitScore(vec);
pairs = findPairs(bitscore);
cout << "Max pairs = " << pairs;
return 0;
}
vector<int> correctBitScores(vector<int> bis) {
int temp = 0;
for (size_t i = 0; i < bis.size(); i++) {
temp = bis[i];
int count = 0;
while (temp > 0) {
temp = temp / 10;
count++;
}
if (count > 2)
bis[i] = abs(100 - bis[i]);
}
/*cout << "\nCorrected" << endl;
for (int i = 0; i < size(bis); i++) {
cout << bis[i] << endl;
}*/
return bis;
}
int findPairs(vector<int> vec) {
int count = 0;
vector<int> odd;
vector<int> even;
for (size_t i = 0; i < vec.size(); i++)
(i % 2 == 0 ? even.push_back(vec[i]) : odd.push_back(vec[i]));
for (size_t j = 0; j < odd.size(); j++)
for (size_t k = j + 1; k < odd.size(); k++) {
if (odd[j] / 10 == odd[k] / 10) {
count++;
odd.erase(odd.begin()+j);
}
}
for (size_t j = 0; j < even.size(); j++)
for (size_t k = j + 1; k < even.size(); k++) {
if (even[j] / 10 == even[k] / 10) {
count++;
even.erase(even.begin() + j);
}
}
return count;
}
vector<int> bitScore(vector<int> v) {
int temp = 0, rem = 0;
vector<int> bs;
for (size_t i = 0; i < v.size(); i++) {
int max = 0, min = 9;
temp = v[i];
while (temp > 0) {
rem = temp % 10;
if (min > rem)
min = rem;
if (max < rem)
max = rem;
temp = temp / 10;
}
int bscore = (max * 11) + (min * 7);
bs.push_back(bscore);
}
/*cout << "\nBit Scores = " << endl;
for (int i = 0; i < size(bs); i++) {
cout << bs[i] << endl;
}*/
bs = correctBitScores(bs);
return bs;
}
I tried doing it very simple c++ code as per my understanding of Que,can you just verify it more test cases.
#include <bits/stdc++.h>
using namespace std;
int main() {
int n,count=0;
cin>>n;
vector<int>v(n);
for(int i=0;i<n;i++){
cin>>v[i];
string s = to_string(v[i]);
sort(s.begin(),s.end());
int temp = (s[s.length()-1]-'0')*11 + (s[0] - '0')*7;
v[i] = temp%100;
}
unordered_map<int ,vector<int>>o,e;
for(int i=0;i<n;i=i+2){
o[v[i]/10].push_back(i+1);
}
for(int i=1;i<n;i=i+2){
e[v[i]/10].push_back(i+1);
}
count=0;
for(int i=0;i<10;i++){
int os=o[i].size(),es=e[i].size();
if(os==2)
count++;
if(es == 2)
count++;
if(os>2 || es>2)
count += 2;
}
cout<<count;
}
I am solving a problem in which I have to find those element from the array whose total gives maximum sum. But there is a condition that no two adjacent element can be the part of that max subarray. Here is my code using simple brute Force solution-
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin >> t;
while (t != 0)
{
int n, i, s, k = 0, m = -1001;
vector< int > a;
cin >> n;
a.resize(n, 0);
vector< int > b;
for (i = 0; i < n; i++)
{
cin >> a[i];
m = max(m, a[i]);
if (a[i] < 0)
{
a[i] = 0;
++k;
}
}
if (k == n)
cout << m;
else
{
k = 0;
s = a[0];
b.push_back(a[0]);
for (i = 1; i < n; i++)
{
if (i != k + 1)
{
if (a[i])
{
s += a[i];
b.push_back(a[i]);
k = i;
}
}
else
{
if (s - a[i - 1] + a[i] > s)
{
b.pop_back();
s -= a[i - 1];
s += a[i];
b.push_back(a[i]);
++k;
}
}
}
}
cout << endl;
for (i = n; i >= 0; i--)
{
if (b[i])
cout << b[i] << " ";
}
cout << endl;
--t;
}
return 0;
}
Here is input to code-
First line represent no. of test cases,
Second line represent size of array
And the next line shows array elements.m
5
5
-1 7 8 -5 4
4
3 2 1 -1
4
11 12 -2 -1
4
4 5 4 3
4
5 10 4 -1
Output-
4 8
32 32607 -787829912 1 3
32 32607 -787829912 12
3 5
10
Expected output-
4 8
1 3
12
3 5
10
So, there are 5 test cases. For the first test case and last two test case output is correct. But for second and third test case it is giving garbage value. What is the problem, that for some test cases it is giving garbage value, and for other not.
for (i = n; i >= 0; i--)
{
if (b[i])
cout << b[i] << " ";
}
This prints out n+1 values in b. But even in the best case, b only has n values (for n=1). And for n>1, b.size() is less than n, so you are reading garbage from outside the vector's storage (this is undefined behavior). Just use the correct bound:
for (i = b.size() - 1; i >= 0; ++i)
I think I found your (first) problem:
if(k==n)
cout<<m;
When all numbers are negative this outputs the largest of them.
But the empty array has a sum of 0 and is larger than a negative number and has no 2 adjacent members in it. So clearly the right answer should be 0, not m.
I have a small problem. I'm working on a project that have to print all the partitions of an integer, in this way. For example:
5 = 5
5 = 4 + 1
5 = 3 + 2
5 = 3 + 1 + 1
5 = 2 + 2 + 1
5 = 2 + 1 + 1 + 1
5 = 1 + 1 + 1 + 1 + 1
.
So there is my solution:
#include <iostream>
using namespace std;
void printArray(int p[], int n) {
for (int i = 0; i < n; i++)
cout << p[i]<<" + " ;
cout<<endl;
}
void printAllUniqueParts(int n) {
int p[n];
int k = 0;
p[k] = n;
while (true)
{
cout<<n<<" = ";
printArray(p, k + 1);
int rem_val = 0;
while (k >= 0 && p[k] == 1)
{
rem_val += p[k];
k--;
}
if (k < 0)
return;
p[k]--;
rem_val++;
while (rem_val > p[k])
{
p[k + 1] = p[k];
rem_val = rem_val - p[k];
k++;
}
p[k + 1] = rem_val;
k++;
}
}
It prints them in a correct order, but the problem is that it prints an extra + at the end. I can't find the problem. It may be very small bug, but I cant see it. Could you please check this out, and share your ideas?
Only print the "+" if you are not at the end of the range.
cout << p[i]; if (i+1 < n) cout << " + " ;
The problem is very obvious:
for (int i = 0; i < n; i++)
cout << p[i]<<" + " ;
The code you wrote prints a + after every number. So that's exactly what it's going to do. Just because you don't want a + to appear after the last number, that's not going to happen unless the program is coded to do so.
There are several common, simplest techniques for formatting this kind of output. The simplest one is not to print the + after the number, but before it, and simply not print it before the first number. It's often logically simpler to take a non-default option for the first step, instead of the last one, since you do not have to figure out which one is the last one:
for (int i = 0; i < n; i++)
{
if (i > 0)
cout << " + ";
cout << p[i];
}
Okay, so I'm a complete noob. I'm trying my hand at Project Euler to get better at C++. I'm doing problem #1, but I'm not getting the correct output. When I run it, I get that numTotalThree is -3, and numTotalFive is -5, and that numTotal is 0. There's something wrong with my functions, but I'm not sure what I've done wrong. How do I fix this?
#include <iostream>
using namespace std;
int main()
{
int amount = 1000;
int numOfThree = amount / 3;
int numOfFive = amount / 5;
int numTotalThree = 0;
int numTotalFive = 0;
int numTotal = numTotalThree + numTotalFive;
cout << numOfThree << endl;
cout << numOfFive << endl;
for(int i = 0; i <= numOfThree; i++)
{
numTotalThree += numTotalThree + 3;
}
cout << numTotalThree << endl;
for(int i = 0; i <= numOfFive; i++)
{
numTotalFive += numTotalFive + 5;
}
cout << numTotalFive << endl;
cout << numTotal << endl;
system("PAUSE");
return 0;
}
I guess you need something like this:
int sum = 0;
for (int i =0; i < 1000; ++i){
if(i % 3 == 0 || i % 5 == 0){
sum += i;
}
}
Later edit: I don't know why you want to count the numbers divisible with 3 or 5 that are less than 1000. The problem (Project Euler - Problem 1) asks for the sum of all the numbers less than 1000, divisible with 3 or 5.
C++ is not a functional language it's procedural - that means you have to do things in order. When you do this:
int numTotalFive = 0;
int numTotal = numTotalThree + numTotalFive;
It will be executed then and there and not again when numTotalThree and numTotalFive are updated. If you don't touch it again that's the value that will be output.
Here's an idea to go on:
Check how many are divisible by three by checking that the remainder %==0. Do the same for five, and then for both of them. Subtract from the total of the first two the number that is divisible by both to get an accurate answer.
int divisibleByThree=0;
int divisibleByFive=0;
int divisibleByBoth=0;
int total;
for(int i=0; i<1000; i++)
{
if (i%3==0)
divisibleByThree++;
if (i%5==0)
divisibleByFive++;
if (i%5==0) && i%5==0)
divisibleByBoth++;
}
total = divisibleByThree + divisibleByFive - divisibleByBoth;
return total;
Your
numTotalThree is overflowing for n in [0, 333]
3/2*(-2 + 2n)
Similarly numTotalFive for n in [0, 200]
5/2*(-2 + 2n)
So you're seeing negative values.
As other suggested you probably need to revisit your logic.
All you need is just to sum up the numbers in [0,1000] that are divisible by 3 or 5
size_t total =0;
for (size_t x =0; x < 1000; x++){
if( (x % 3 == 0) || (x % 5 == 0) ){
total += x;
}
}