Rashed Sami Rashed Sami - 22 days ago 5
C++ Question

how to find the odd numbers from below programs divisors?

#include <iostream>

using namespace std;

int main()
{ int i,num1,num2,sum=0,count=0;
cout<<"Enter a range: ";
cin>> num1>> num2;
for(i = num1;i <= num2; i++)

if(i%3 ==0 ||i%5 ==0)
{

count++;
//sum=sum+i;
cout<<i<<" ";
}

return 0;
}


I did a program of finding the divisors of 3 and 5 in a given range, but now i want to find the odd numbers from that divisors.how to do that???
suppose for this program i enter the range 1 to 20.And i will get divisors:3,5,6,10,12,15,18,20.Now i want to get odd numbers from this numbers.How to do that??

Answer

If you want to check if i is odd, simply add i % 2!= 0 into the condition. Also as leaf pointed out, don't use using namespace std; and while you're there, why not actually use the variable count?

#include <iostream>

int main(){
    int low{ 0 };
    int max{ 0 };
    std::cout << "Type in low: ";
    std::cin >> low;
    std::cout << "Type in max: ";
    std::cin >> max;

    unsigned int count{ 0u };

    for (int i = low; i < max; ++i){
        if (i % 2 != 0 && (i % 3 == 0 || i % 5 == 0)){
            ++count;
            std::cout << i << " ";
        }
    }
    std::cout << "\nNumber of odd integers that are multiples of 3 or 5 found: " << count << std::endl;

    return 0;
}

Example run:

Type in low: 300
Type in max: 795
303 305 309 315 321 325 327 333 335 339 345 351 355 357 363 365 369 375 381 385
387 393 395 399 405 411 415 417 423 425 429 435 441 445 447 453 455 459 465 471
475 477 483 485 489 495 501 505 507 513 515 519 525 531 535 537 543 545 549 555
561 565 567 573 575 579 585 591 595 597 603 605 609 615 621 625 627 633 635 639
645 651 655 657 663 665 669 675 681 685 687 693 695 699 705 711 715 717 723 725
729 735 741 745 747 753 755 759 765 771 775 777 783 785 789
Number of odd integers that are multiples of 3 or 5 found: 115